Igo*_*dro 7 kotlin-coroutines kotlinx.coroutines.flow
我正在使用RxJavatoCoroutines和替换我当前的实现Flow。我在使用某些Flow运算符时遇到了一些问题。
我试图Flow在提供它以被收集之前过滤 a 中的项目列表。( Flow<List<TaskWithCategory>>)
以下是示例Rx2:
repository.findAllTasksWithCategory()
.flatMap {
Flowable.fromIterable(it)
.filter { item -> item.task.completed }
.toList()
.toFlowable()
Run Code Online (Sandbox Code Playgroud)
在上面的实现中,我提供了一个已经完成的TaskWithCategory过滤列表Task。
我怎样才能做到这一点Flow?
鉴于唯一使用的运算符是filter内部 flowable 是不必要的,因此流实现非常简单:
repository.findAllTasksWithCategoryFlow()
.map { it.filter { item -> item.task.completed } }
Run Code Online (Sandbox Code Playgroud)
如果更多地涉及内部转换(让我们使用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.
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4329 次 |
| 最近记录: |