RunBlocking and coroutineScope builders
RunBlocking and coroutineScope builders may look similar because they both wait for their body and all its children to complete.
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.
Because of that difference, runBlocking is a regular function and coroutineScope is a suspending function.
A coroutineScope builder can be used inside any suspending function to perform multiple concurrent operations.
Let's launch two concurrent coroutines inside a doWorld suspending function:
// Sequentially executes doWorld followed by "Done"
fun main() = runBlocking {
doWorld()
println("Done")
}
// Concurrently executes both sections
suspend fun doWorld() = coroutineScope { // this: CoroutineScope
launch {
delay(2000L)
println("World 2")
}
launch {
delay(1000L)
println("World 1")
}
println("Hello")
}
You will see the following result:
Hello
World 1
World 2
Done