【发布时间】:2020-10-03 14:53:33
【问题描述】:
我正在尝试使用Flow 模拟BehaviourSubject。
以下示例中的代码无法正常运行,因为collect {} 不允许协程继续:
@FlowPreview
@ExperimentalCoroutinesApi
fun main() = runBlocking {
val scope = CoroutineScope(Dispatchers.IO)
val channel = MutableStateFlow(0)
channel.value++
val flow = channel.broadcastIn(scope).asFlow()
channel.value++
flow.collect { println("First: $it") } // Code will stop executing here ...
flow.collect { println("Second: $it") } // Will not execute
channel.value++ // Wil not execute
return@runBlocking
}
输出:
First: 2
// process not exited
我不认为接受回调也应该持有线程。 问题出在哪里?
这样的问题不会发生在感冒Flow:
fun main() = runBlocking {
val data = listOf(1, 2, 3, 4, 5).asFlow()
data.collect { println(it) }
println("Done")
}
输出:
1
2
3
4
5
Done
我错过了什么吗?
科特林:
1.4.10
协程:1.3.9
【问题讨论】: