1

我在带有 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()))
        }
    }

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

4

1 回答 1

1

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

像这样:

val data = repository.getIOTCameraData(1, 10).asFlow().first { 
    responseStatusIdentification(it)
}
_iotCameraData.postValue(data.data)
于 2021-05-28T03:49:02.460 回答