【发布时间】:2023-03-07 06:42:01
【问题描述】:
我正在阅读 Coroutine Basics 试图理解和学习它。
这里有一段代码:
fun main() = runBlocking { // this: CoroutineScope
launch {
delay(200L)
println("Task from runBlocking")
}
coroutineScope { // Creates a new coroutine scope
launch {
delay(900L)
println("Task from nested launch")
}
delay(100L)
println("Task from coroutine scope") // This line will be printed before nested launch
}
println("Coroutine scope is over") // This line is not printed until nested launch completes
}
输出如下:
Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over
我的问题是为什么这行:
println("Coroutine scope is over") // This line is not printed until nested launch completes
总是最后调用?
它不应该被调用,因为:
coroutineScope { // Creates a new coroutine scope
....
}
被暂停了?
那里还有一个注释:
runBlocking 和 coroutineScope 的主要区别在于后者在等待所有子进程完成时不会阻塞当前线程。
我不明白 coroutineScope 和 runBlocking 在这里有何不同? coroutineScope 看起来像它的阻塞,因为它只在完成后才到达最后一行。
有人能告诉我吗?
提前致谢。
【问题讨论】:
-
你还可以找到关于
coroutineScopeinsightful...的文档。 -
应该更新文档以更好地解释这一点,因为您不是唯一一个以这种方式解释它的人。
-
Kotlin 的文档如此糟糕,不断抛出概念,解释混乱。