如何将kotlinx.coroutines.flow列表转换为普通数据类列表。
发布于 2020-01-02 18:04:43
由于您希望从嵌套列表流转到单个列表,因此需要一个平面映射操作:
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)
}发布于 2020-01-01 17:40:14
当我们将Flow<List<T>>转换为List<T>时,我们需要返回List<T>。Flow是一种本机反应式编程解决方案,用于处理冷数据流。返回值是没有意义的,因为计算发生在不同的线程中。Reactive programming意味着消除returning value和基于data being received的react的想法。如果您仍然需要返回值,我们需要使用分块数据结构来计算该值,然后返回它。但是在Android世界中,阻塞并不是一个好的选择。
https://stackoverflow.com/questions/59550674
复制相似问题