Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert coroutines Flow<List<T>> to List<T>

How to convert kotlinx.coroutines.flow list to normal data class list.

like image 992
Dashrath Rathod Avatar asked Jan 01 '20 07:01

Dashrath Rathod


1 Answers

Since you want to go from a flow of nested lists to a single list, you need a flat-mapping operation:

suspend fun <T> Flow<List<T>>.flattenToList() = 
        flatMapConcat { it.asFlow() }.toList()

Example of usage:

suspend fun main() {
    val flowOfLists: Flow<List<Int>> = flowOf(listOf(1, 2), listOf(3, 4))
    val flatList: List<Int> = flowOfLists.flattenToList()
    println(flatList)
}
like image 63
Marko Topolnik Avatar answered Sep 21 '22 02:09

Marko Topolnik