【发布时间】:2021-11-07 15:50:00
【问题描述】:
在这段代码中,好像是协程遇到一个收集到的流就取消了。
fun main() = runBlocking {
println("Hi, world!")
CoroutineScope(Dispatchers.Default).launch {
innerSuspend()
println("Bye, world!")
}.join()
println("task ended.")
}
suspend fun innerSuspend() {
println("run: innerSuspend")
innerFlow().collect {
println("innerCallback : $it")
}
}
suspend fun innerFlow() = callbackFlow {
trySend("U r world?")
awaitClose { close() }
}
我希望上面代码的结果看起来像这样:
嗨,世界!
运行:innerSuspend
innerCallback : 你的世界?
再见,世界!
任务结束。
但是,出乎意料,Bye, world!却没有显示出来。
嗨,世界!
运行:innerSuspend
innerCallback : 你的世界?
为什么会发生这种情况,我该如何解决?
【问题讨论】:
-
另外,调用
launch { .. }.join()没有意义,你也可以调用suspend函数。如果您确实想切换调度程序,只需使用withContext(Dispatchers.Default) { ... }包装您的暂停调用。
标签: kotlin kotlin-coroutines coroutine flow