首页 > 解决方案 > 如何转换流流动> 在科特林?

问题描述

我有一个完整的项目流,比如 Flow。我想将此流转换为 Flow<List> 并列出所有项目。

我试过用

public fun <T> Flow<T>.toList(): Flow<List<T>> = flow {
    val list = toList(mutableListOf())
    emit(list.toImmutableList())
}

但是这个函数从不发出值

标签: kotlinkotlin-flow

解决方案


如果您真正想要的是一个包含单个List<T>元素的流程,那么我认为您做对了。单个元素将是初始流程中所有项目的列表。

我认为您的问题可能是该Flow.toList()功能已经存在。尝试不同的命名:

fun main(args: Array<String>) = runBlocking {
  val initialFlow = List(5) { it }.asFlow()
  
  initialFlow.toSingleListItem().collect {
      println(it)
  }
}

public fun <T> Flow<T>.toSingleListItem(): Flow<List<T>> = flow {
    val list = toList(mutableListOf())
    emit(list)
}

你可以在这里运行它: https ://pl.kotl.in/frCg831WM


推荐阅读