kotlin - 如何转换流流动> 在科特林?
- > 在科特林?
问题描述
我有一个完整的项目流,比如 Flow。我想将此流转换为 Flow<List> 并列出所有项目。
我试过用
public fun <T> Flow<T>.toList(): Flow<List<T>> = flow {
val list = toList(mutableListOf())
emit(list.toImmutableList())
}
但是这个函数从不发出值
解决方案
如果您真正想要的是一个包含单个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
推荐阅读
- php - 相同字符串之间的比较失败
- ios - 当我单击表格视图中的复选框时,一个标签内的数量应添加到 iOS 中的另一个标签
- python - 使用抛出“df未定义”错误的函数创建熊猫数据框
- django - Django:在管理页面中将 ManyToManyField 显示为表格
- html - 图片未显示在 Gmail/Yahoo 邮件中
- javascript - 使用 React 从表中删除项目后重新加载表
- android - android TextWatcher beforeTextChanged 问题
- java - 在 POM uisng 页面工厂中获取 java.lang.NullPointerException
- c# - 使用域模型反序列化物理上不兼容的 JSON
- javascript - 过滤子数组