我正在使用替换当前的实现RxJava
to Coroutines
and Flow
。我在使用一些时遇到一些问题Flow
运营商。
我正在尝试过滤 a 中的项目列表Flow
在提供收集之前。 (Flow<List<TaskWithCategory>>
)
这是关于的示例Rx2
:
repository.findAllTasksWithCategory()
.flatMap {
Flowable.fromIterable(it)
.filter { item -> item.task.completed }
.toList()
.toFlowable()
在上面的实现中,我提供了一个列表TaskWithCategory
过滤依据Task
已经完成的。
我怎样才能实现这个使用Flow
?
鉴于唯一使用的运算符是filter
内部的 flowable 是不必要的,使得流的实现非常简单:
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.
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)