[英]Will the collect of the Flow block to execute?
我运行代码 A 并得到结果 A。在我看来,它应该是结果 B。
似乎flow.collect { value -> println(value) }
块要执行。
Flow块的collect会执行吗?
代码 A
fun simple(): Flow<Int> = flow {
println("Flow started")
for (i in 1..3) {
delay(300)
emit(i)
}
}
fun main() = runBlocking<Unit> {
println("Calling simple function...")
val flow = simple()
println("Calling collect...")
flow.collect { value -> println(value) } //Block?
println("Calling collect again...")
}
结果 A
Calling simple function...
Calling collect...
Flow started
1
2
3
Calling collect again...
结果乙
Calling simple function...
Calling collect...
Flow started
Calling collect again...
1
2
3
顺便说一句,我运行代码 1 并按预期获得结果 1。
代码 1
fun simple(): Flow<Int> = flow {
for (i in 1..3) {
delay(100)
emit(i)
}
}
fun main() = runBlocking<Unit> {
launch {
for (k in 1..3) {
println("I'm not blocked $k")
delay(100)
}
}
simple().collect { value -> println(value) }
}
结果 1
I'm not blocked 1
1
I'm not blocked 2
2
I'm not blocked 3
3
挂起函数不会阻塞,但它们是同步的,这意味着协程中代码的执行会等待挂起函数返回,然后才能继续。 挂起函数调用和阻塞函数调用的区别在于,在协程等待挂起函数返回的同时,线程被释放以用于其他任务。
collect
是一个挂起函数,它在内部重复且同步地(挂起,不阻塞)调用其 lambda,并且在 Flow 完成之前不会返回。
launch
是一个启动协程的异步函数。 它立即返回而无需等待其协程完成,这就是代码 1 表现如您所愿的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.