我正在尝试学习协程,但我仍然遇到一些基本问题。 我有一个发出一系列项目的流,我想将该流拆分为 2 个流。这就是我在 RxJava 中的写法:
val list = Flowable.just(1..6).share()
val even = list.filter { it % 2 == 0 }.subscribe { println(it) } // 2, 4, 6
val odd = list.filter { it % 2 == 1 }.subscribe { println(it) } // 1, 3, 5
我如何使用 Kotlin 协程流程复制它?提前致谢。
最佳答案
一个家庭sharing operators (以及 a hot SharedFlow
)正在努力简化您正在寻找的工作流类型(使用 Kotlin Flows)。
与此同时,流在本质上确实是冷的(因此您不能真正按原样共享它们),但它们仍然可以共享热源来实现您的需要。我提供了有关如何执行此操作的详细信息 in this answer .
简而言之,最终结果如下所示:
val original: Flow<String> = flowOf("aap", "noot", "mies", "wim", "zus","jet","weide","does")
// create an implicit hot BroadcastChannel, shared between collectors
// so that they each get all elements (which are each produced only once)
val sharedFlow = original.broadcastIn(scope).asFlow()
// create derived cold flows, which will subscribe (on collect) to the
// same hot source (BroadcastChannel)
val flow1 = sharedFlow.filter { it.length == 4 }
val flow2 = sharedFlow.filter { it.length == 3 }.map { it.toUppercase() }
flow1.collect { it -> println("Four letter: ${it}") }
flow2.collect { it -> println("Three letter: ${it}") }
(这很快将被 SharedFlow
取代。)
关于android - 如何将 Kotlin 流程拆分为 2 个流程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807545/