【问题标题】:How to convert coroutines Flow<List<T>> to List<T>如何将协程 Flow<List<T>> 转换为 List<T>
【发布时间】:2020-01-01 07:17:54
【问题描述】:

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

【问题讨论】:

  • 您不能直接将其转换为列表,但您所能做的就是使用collectmap 等方法将其作为列表使用

标签: android kotlin kotlin-coroutines


【解决方案1】:

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

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

使用示例:

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

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2019-04-13
    • 1970-01-01
    • 2019-05-20
    相关资源
    最近更新 更多