runBlocking bridges ordinary blocking code and suspending functions. It creates and runs a coroutine, blocks the current thread until completion, and lets its body call suspending functions. section 14.6 section 14.6.1
Listing 14.6 Using runBlocking to invoke a suspending function
import kotlinx.coroutines.*
import kotlin.time.Duration.Companion.milliseconds
suspend fun doSomethingSlowly() {
delay(500.milliseconds) #1
println("I'm done")
}
fun main() = runBlocking {
doSomethingSlowly()
}
A compact Kotlin program uses runBlocking to call doSomethingSlowly, which suspends with delay before printing. section 14.6.1
Inside the block, delay suspends the coroutine rather than blocking additional threads. This makes runBlocking useful as an entry point into coroutine code, while launch can start child coroutines within it. section 14.6.1
Structured concurrency gives runBlocking a defined completion boundary:
- The block establishes a coroutine scope, so launch and async coroutines created inside it become children. section 15.1
- runBlocking waits for its child coroutines and their descendants before returning, even when its own body finishes earlier. section 15.1
