Kotlin says
- runBlocking method blocks the current thread for waiting
- coroutineScope just suspends, releasing the underlying thread for other usages.
- hence runBlocking is a regular function and coroutineScope is a suspending function
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
}
in above example what i expect is :-
- runBlocking blocks main thread and
launch
will executed and it comes todelay(200L)
- So, underlying coroutine is released and runs
coroutineScope
and comes todelay(500L)
&delay(100L)
- So, again underlying coroutine is released and it should print
println("Coroutine scope is over")
.
This is what my understanding on runBlocking
and coroutineScope
. Which is not working as expected.
the Output is
Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over
Can anyone kindly explain in a easy way to understand this.