根据Kotlin文档,CoroutineScope不会阻塞当前线程。他们显示了以下代码示例:
fun main() = runBlocking { // this: CoroutineScope
launch {
delay(200L)
println("Task from runBlocking")
}
coroutineScope { // Creates a coroutine scope
launch {
delay(500L)
println("Task from nested launch")
}
delay(100L)
println("Task from coroutine scope") // This line will be printed before the nested launch
}
println("Coroutine scope is over") // This line is not printed until the nested launch completes
}
输出如下:
Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over
它们甚至包括评论:
直到嵌套启动完成后才打印此行
当然,该行直到结束才显示。但这是我不明白的。他们说CoroutineScope不会阻塞当前线程。那么,为什么在第一次启动完成后不打印此行?
println("Coroutine scope is over")
此行不属于coroutineScope。我期望结果是:
Coroutine scope is over
Task from runBlocking
Task from coroutine scope
Task from nested launch