as Coroutine's document says: "The main difference...
# announcements
m
as Coroutine's document says: "The main difference is that the runBlocking method blocks the current thread for waiting, while coroutineScope just suspends, releasing the underlying thread for other usages." and the code below works as it expected:
Copy code
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
}
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?
k
runBlocking()
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.
Copy code
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
}
m
Thanks a lot, amazing!!!