简体   繁体   English

Kotlin 中流发出的并行处理值

[英]Parallel processing values emitted by flow in Kotlin

Kotlin code Kotlin代码

runBlocking {
    flow {
        for (i in 0..4) {
            println("Emit $i")
            emit(i)
        }}  .onEach { if (it%2 == 0) delay(200) // Block 1
                println("A: got $it")
            }
            .onEach { println("B: got $it") } // Block 2
            .collect()
}

print in console:在控制台打印:

Emit 0
A: got 0
B: got 0
Emit 1
A: got 1
B: got 1
Emit 2
...

How can I run parallel process both block1 & block2 to get messages from block 2 before block 1 in half cases?在一半的情况下,如何同时运行 block1 和 block2 以在 block 1 之前从 block 2 获取消息?

You could try to launch separate coroutines in those blocks:您可以尝试在这些块中启动单独的协程:

private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())

flow {
    for (i in 0..4) {
        println("Emit $i")
        emit(i)
    }
}.onEach { // Block 1
    scope.launch {
        if (it % 2 == 0) delay(200) 
        println("A: got $it")
    }

}.onEach { // Block 2
    scope.launch { 
        println("B: got $it") 
    }
}.launchIn(scope)

In this case Block 2 will be printed before Block 1 .在这种情况下, Block 2将在Block 1之前打印。 SupervisorJob needs here to prevent cancelling launched coroutines when one of them fails. SupervisorJob需要在这里防止在其中一个失败时取消已启动的协程。

This solution doesn't guarantee the order, eg there can be logs in the next order:此解决方案不保证顺序,例如下一个顺序可能有日志:

Emit 0
Emit 1
Emit 2
Emit 3
Emit 4

B: got 0
A: got 1
B: got 1
B: got 2
A: got 3
B: got 3
B: got 4
A: got 0
A: got 2
A: got 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM