如何将协程 Flow<List<T>> 转换为 List<T>

Das*_*hod 4 android kotlin kotlin-coroutines

如何将 kotlinx.coroutines.flow 列表转换为普通数据类列表。

Mar*_*nik 10

由于您想从嵌套列表流转换为单个列表,因此需要平面映射操作:

suspend fun <T> Flow<List<T>>.flattenToList() = 
        flatMapConcat { it.asFlow() }.toList()
Run Code Online (Sandbox Code Playgroud)

用法示例:

suspend fun main() {
    val flowOfLists: Flow<List<Int>> = flowOf(listOf(1, 2), listOf(3, 4))
    val flatList: List<Int> = flowOfLists.flattenToList()
    println(flatList)
}
Run Code Online (Sandbox Code Playgroud)