https://kotlinlang.org logo
Title
k

Koya Sivaji

08/03/2020, 9:50 PM
Hi, am new to coroutines and flows and facing an issue with usage of Flows. Below is the code
DeviceDao{
@Query("SELECT * FROM devices")
    abstract fun getAllDevices(): Flow<List<Device>>
}
Repository layer
fun getAllDevices() = database.deviceDao().getAllDevices()
This repository method called form view model as below and every thing works fine
viewModelScope.launch {
            homes = homeRepository.homes.asLiveData()
            devices = deviceRepository.getAllDevices().asLiveData()
        }
Issue I am facing: Added another method at repository layer like below
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

octylFractal

08/03/2020, 9:53 PM
I suspect that
getAllDevices()
never finishes for some reason, you'd have to consult whatever implements that
o

okarm

08/03/2020, 10:14 PM
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

Koya Sivaji

08/03/2020, 10:46 PM
Thanks @okarm,
database.deviceDao().getAllDevices().first()
is working. Yes, @octylFractal flow never terminated when I call
database.deviceDao().getAllDevices().collect {
        localDevices = it
      }
Thank you guys for the help