【问题标题】:Live Data issue inside Loop循环内的实时数据问题
【发布时间】:2021-05-27 03:18:56
【问题描述】:

我在带有 Loop 的 viewModel 中有一个 IOTCamera 函数。该函数应基于“selectedSlot”参数重复调用存储库 GET 函数,延迟为 1 分钟。我的问题是循环(重复())无法正常工作。它适用于第一次迭代。但是第二次迭代永远不会被调用。

  fun getIOTCameraData(repository: MainRepository, selectedSlot: Int)= viewModelScope.launch(Dispatchers.Default){
        repeat(selectedSlot){
            repository.getIOTCameraData(1, 10).asFlow().collect {data->
                if (responseStatusIdentification(data)) {
                    _iotCameraData.postValue(data.data)//Update live data instance for UI
                }
            }
            delay(60000)
        }
    }

存储库函数将调用 Retrofit GET API 并收集数据。

 suspend fun getIOTCameraData(page: Int, perPage: Int) = liveData<Resource<IOTCameraResponse>> {
        emit(Resource.loading())
        try {
            val response = iotCameraService?.getIOTCameraData(token = IOT_CAMERA_AUTH, page = page, perPage = perPage)
            emit(Resource.success(response))
        } catch (e: Exception) {
            emit(Resource.error(e.message.toString()))
        }
    }

如果有人知道原因,请更新。

【问题讨论】:

    标签: android android-livedata kotlin-coroutines android-viewmodel android-livedata-transformations


    【解决方案1】:

    collect 的调用永远不会返回。如果您只需要获取单个值并结束收集,那么您应该调用first()

    像这样:

    val data = repository.getIOTCameraData(1, 10).asFlow().first { 
        responseStatusIdentification(it)
    }
    _iotCameraData.postValue(data.data)
    

    【讨论】:

    • 但在这种情况下,getIOTCameraData 挂起函数可能会发出两次。第一个发射将是加载状态,剩下的发射是成功或来自 HTTP 响应的错误。 responseStatusIdentification() 函数实际上是在处理加载状态。所以我的问题是 .first() 是否会返回两次?
    • 终端操作符返回流发出的第一个元素,然后取消流的集合。据我了解, .first() 将取消剩余的流程。
    • 我已编辑我的回复以过滤掉不成功的回复。我为此发明了一个isSucces 属性,但这可能是您的responseStatusIdentification() 函数。编辑:我只是假设。
    • 只使用带有谓词的first() 函数可能会好一点...我将编辑回复=)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 2021-08-29
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    相关资源
    最近更新 更多