循环内的实时数据问题

Live Data issue inside Loop

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

  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()))
        }
    }

如果有人知道这是什么原因,请更新。

从未 returns 调用 collect。如果您只需要获取单个值并结束收集,那么您应该改为调用 first()

像这样:

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