Я немного изменил ваш код
fun main() = runBlocking(Dispatchers.Default) {
var i = 1
launch {
println("Task from runBlocking")
while (i < 10) {
delay(30L)
println(i++)
}
}
coroutineScope { // Creates a coroutine scope
launch {
delay(200L)
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")
}
Вывод
Task from runBlocking
1
2
3
Task from coroutine scope
4
5
6
Task from nested launch
Coroutine scope is over
7
8
9
Наблюдение, которое я сделал,
Итак, после печати 3 Task from coroutine scope
и после печати 6 Task from nested launch
.
, затем точно после этого Coroutine scope is over
, но вы все равно можете увидеть напечатанное l oop 7,8,9
.
Это потому, что runBlocking
coroutineScope
ждет, пока все его члены не выполнятся, приостановив базовые потоки. Но поймите, эти потоки сначала работают с членами coroutineScope
, а не с runBlocking
.
Следовательно, это печать Task from coroutine scope
и Task from nested launch
до Coroutine scope is over