Live Data issue inside Loop

574 Views Asked by At

I have an IOTCamera function inside viewModel with Loop. The function should repeatedly call the repository GET function based on the "selectedSlot" parameter with a delay of 1 minute. My problem here is the loop(repeat()) is not working properly. It's working for the first iteration. But the second iteration never gets called.

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

The repository function will call the Retrofit GET API and it will collect the data.

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

Please update if anyone know the reason for this.

1

There are 1 best solutions below

4
On BEST ANSWER

The call to collect never returns. If you just need to get a single value and end collecting then you should call first() instead.

Like this:

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