Hi, am new to coroutines and flows and facing an i...
# coroutines
k
Hi, am new to coroutines and flows and facing an issue with usage of Flows. Below is the code
Copy code
DeviceDao{
@Query("SELECT * FROM devices")
    abstract fun getAllDevices(): Flow<List<Device>>
}
Repository layer
Copy code
fun getAllDevices() = database.deviceDao().getAllDevices()
This repository method called form view model as below and every thing works fine
Copy code
viewModelScope.launch {
            homes = homeRepository.homes.asLiveData()
            devices = deviceRepository.getAllDevices().asLiveData()
        }
Issue I am facing: Added another method at repository layer like below
Copy code
private suspend fun deleteDevicesNotInLambdaResponse(deviceJsonList: List<Device>) {

    var localDevices = emptyList<Device>()
    database.deviceDao().getAllDevices().collect {
        localDevices = it
      }


//. the below code never executes

        val localDeviceIds = localDevices.map { it.deviceId }
        val remoteDeviceIds = deviceJsonList.map { it.deviceId }

        val localDevicesNotInLambdaResponse = localDeviceIds.filterNot {     remoteDeviceIds.contains(it) }
        database.deviceDao().deleteDevices(localDevicesNotInLambdaResponse)
    
}
Basically, here I want to get all local devices and find out which are not in API response and delete those devices from local data base As commented above, the code below the comment
the below code never executes
got never executed. Looks like I am missing some thing about how the Flow operator works Please suggest me how to fix this issue
o
I suspect that
getAllDevices()
never finishes for some reason, you'd have to consult whatever implements that
o
val localDevices = database.deviceDao().getAllDevices().first()
will help you. Alternatively add a suspend method to your Dao, which just returns
List<Device>
This question would be better off in #android
On a philosophical note, you should really clean up your function and parameter and variable names.
k
Thanks @okarm,
database.deviceDao().getAllDevices().first()
is working. Yes, @octylFractal flow never terminated when I call
Copy code
database.deviceDao().getAllDevices().collect {
        localDevices = it
      }
Thank you guys for the help