【问题标题】:Does LiveDataScope block of code runs only one time after emit()?LiveDataScope 代码块在 emit() 之后是否只运行一次?
【发布时间】:2020-03-02 17:49:39
【问题描述】:

如标题中所述,LiveDataScope 代码块在 emit() 之后是否只运行一次? 是否可以让我的 LiveDataScope 代码块运行多次,因为我需要向服务器发出请求,如果失败我想调用相同的代码再试一次。

代码示例:

    fun refreshLiveDataResource() = liveData(Dispatchers.Main){
        val retriveRoutes = remoteDataSourceKt.getRoutes()
        if(retriveRoutes.data != null){
            routeList = retriveRoutes.data
        }
        emit(retriveRoutes)
      }

当我调用这个函数时,如果我再次调用函数,在 emit() 之后,永远不会进入。

【问题讨论】:

    标签: android kotlin androidx android-livedata kotlin-coroutines


    【解决方案1】:

    您应该创建一次LiveData,并在需要时更新它的值,而不是每次想要重试时都创建一个新值。我会改用Flow 来更新LiveData,使用retry 运算符以防出现一些错误,如下所示:

    val routesLiveData =
        remoteDataSourceKt.getRoutes()
            .onEach { retriveRoutes ->
                if(retriveRoutes.data != null){
                    routeList = retriveRoutes.data
                }
            }
            .retry(3) { e -> // retries up to 3 times; no argument means retrying forever
                (e is IOException) // retry on any IOException but also introduce delay if retrying
                    .also {
                        if (it)
                            delay(1000)
                    }
            }
            .asLiveData()
    

    你必须:

    1. 使getRoutes() 方法返回Flow
    2. 确保FlowDispatchers.IO 上工作。
    3. 在您的 UI 中观察 myLiveData

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多