Home > OS >  Collect in Activity/Fragment Object from Room Flow<List<Object>>
Collect in Activity/Fragment Object from Room Flow<List<Object>>

Time:09-01

DAO:

@Query("SELECT * FROM CarTable")
fun getAllCars(): Flow<List<CarEntity>>

Repository:

class CarsRepository @Inject constructor(
      private val carsDao: CarsDao) { 
    fun getCars() = carsDao.getAllCars()
}

ViewModel:

fun cars(): Flow<List<CarEntity>> = repository.getCars()

Fragment:

 viewModel.cars().onEach { list ->
        for (i in list) {
            Log.d(car1, i.color)
            Log.d(car2, i.color)
            }
    }.launchIn(lifecycleScope)

Code works, on every Room insert/delete I receive new list, but I don't like that I need to iterate/use for loop in fragment. How to receive not list, but each Object/car from list in fragment?

CodePudding user response:

If I understand correctly you want a flow of individual items by emitting each item from each list individually from the source flow. You can do this with a flow builder.

val individualCars = flow<CarEntity> {
    repository.getCars().collect { carList ->
        for (car in carList) emit(car)
    }
}
  • Related