Для 1st snippet
вы используете coroutineScope
, который, как вы можете видеть из документации , определяется как функция suspend
, поэтому он блокирует текущий поток, а "Coroutine scope is over"
не печатается до завершения блока coroutineScope
.
Для 2nd snippet
строка "Coroutine scope is over"
печатается до "Task from run blocking"
, потому что ее println выполняется в главном потоке, а launch
- в рабочем. поток еще не закончил свою работу.
fun mainOne() = runBlocking {
launch {
println("Task from runBlocking")
}
// coroutineScope is defined as a suspend function, so it's blocking the current thread
coroutineScope {
launch {
// worker thread, slower than main thread, printed after "Task from coroutine scope"
println("Task from nested launch")
}
// main thread, printed before "Task from nested launch" within CoroutineScope
println("Task from coroutine scope")
}
// main thread is now free to run and it prints the string below
println("Coroutine scope is over")
}
fun mainTwo() = runBlocking {
launch {
// worker thread, slower than main thread, printed after "Coroutine scope is over" due to concurrency
println("Task from runBlocking")
}
// main thread is running and prints the string below before launch job has finished.
// If you put a delay here you'll notice that launch job gets completed before "Coroutine scope is over"
// E.g delay(2000)
println("Coroutine scope is over")
}
Надеюсь, это имеет смысл:)