Search code examples
kotlinandroid-jetpack-composeandroid-roomviewmodel

Convert Flow<List<>> to List<> From Room database


I am trying to get list of player from my room database. Get it in Flow<List> and i convert it to List I want to loop over the list to check which player should get win/lose/draw.

I think is something's wrong with my playerList, becouse i cant even show it in Log.d

val playerList = playerStatsRepository.getAllPlayerStats(tournament.id)
            .flatMapConcat { it.asFlow() }.toList()

my tournamentViewModel https://github.com/DawidSiudeja/Tournament/blob/master/app/src/main/java/com/example/tournamentapp/TournamentViewModel.kt

It's good way to convert Flow to List?


Solution

  • To simply convert a Flow to its containing type, you can use .first(). Note, if this value then later changes after it is first read, .first() won't pick up on this, as it simply reads the first value, then stops observing the flow.

    As you are using Jetpack compose, if this is a value you are using in a composable, you can convert the flow to a state via tournamentViewModel.playerList.collectAsState(initialValue = emptyList())

    Note: That when collecting a Flow as a state you must provide an initial value. To avoid this you could convert your flow to a StateFlow in your viewmodel via the .stateIn(..) method (see docs)

    To directly answer your question, this should resolve your issue:

    val playerList = playerStatsRepository.getAllPlayerStats(tournament.id).first()