GlobalScope 或自定义 CoroutineScope 实例都不起作用:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun makeFlow() = flow {
println("sending first value")
emit(1)
println("first value collected, sending another value")
emit(2)
println("second value collected, sending a third value")
emit(3)
println("done")
}
@InternalCoroutinesApi
fun main() {
val someScope = CoroutineScope(Dispatchers.Default)
someScope.launch {
makeFlow().collect { value ->
println("value is $value")
}
}
GlobalScope.launch {
makeFlow().collect { value ->
println("value is $value")
}
}
}
绝对没有输出或抛出错误
为什么?
更奇怪的是,当我添加一个runBlocking{}
块时,一切都会执行:
val someScope = CoroutineScope(Dispatchers.Default)
someScope.launch {
makeFlow().collect { value ->
println("someScope: value is $value")
}
}
GlobalScope.launch {
makeFlow().collect { value ->
println("GlobalScope: value is $value")
}
}
runBlocking {
makeFlow().collect { value ->
println("runBlocking: value is $value")
}
}
输出:
sending first value
sending first value
sending first value
runBlocking: value is 1
GlobalScope: value is 1
first value collected, sending another value
GlobalScope: value is 2
second value collected, sending a third value
GlobalScope: value is 3
done
someScope: value is 1
first value collected, sending another value
someScope: value is 2
second value collected, sending a third value
someScope: value is 3
done
first value collected, sending another value
runBlocking: value is 2
second value collected, sending a third value
runBlocking: value is 3
done