Mjahangiry75
01/23/2021, 1:39 PMfun 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
}
I made a change to see the difference, I changed the coroutineScope
to runBlocking
and then as the document said runBlocking
blocks the current thread and coroutineScope
suspends but I got the same output. does anybody know why?knthmn
01/25/2021, 1:05 AMrunBlocking()
takes a CoroutineContext
as an argument which defaults to EmptyCoroutienContext
, which uses Dispatchers.Default
. Since the dispatcher has several threads, when you change it to runBlocking(), it only blocks one of those threads. The runBlocking()
can still run on another thread. You can print the thread name to verify it.
If you use a single thread dispatcher, the inner runBlocking()
deadlocks because it blocks the only thread but needs to run on it.
val singleThreadDispatcher = newSingleThreadContext("foo")
fun main() = runBlocking(singleThreadDispatcher) { // this: CoroutineScope
launch {
delay(200L)
println("Task from runBlocking")
}
runBlocking(singleThreadDispatcher) { // 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
}
Mjahangiry75
01/27/2021, 11:26 AM