如何过滤Kotlin流中的列表 [英] How to filter a list inside Kotlin Flow
本文介绍了如何过滤Kotlin流中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
RxJava
toCoroutines
和Flow
替换我当前的实现。我在使用某些Flow
运算符时遇到一些问题。
我正在尝试在提供要收集的项之前筛选Flow
中的项列表。(Flow<List<TaskWithCategory>>
)
以下是Rx2
上的示例:
repository.findAllTasksWithCategory()
.flatMap {
Flowable.fromIterable(it)
.filter { item -> item.task.completed }
.toList()
.toFlowable()
在上面的实现中,我提供了已完成的TaskWithCategory
筛选条件列表。
如何使用Flow
实现此目的?
推荐答案
假设使用的唯一运算符是filter
,则不需要内部可流动对象,从而使流程实现非常简单:
repository.findAllTasksWithCategoryFlow()
.map { it.filter { item -> item.task.completed } }
如果内部转换比较复杂(让我们使用transform: suspend (X) -> TaskWithCategory
):
repository.findAllTasksWithCategoryFlow()
// Pick according to desired backpressure behavior
.flatMap(Latest/Concat/Merge) {
// Scope all transformations together
coroutineScope {
it.map { item ->
// Perform transform in parallel
async {
transform(item)
}
}.awaitAll() // Return when all async are finished.
}
}
这篇关于如何过滤Kotlin流中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文