A coroutine builder function creates a coroutine and provides an entry point for calling suspending functions from regular code. The main builders divide responsibility by execution and result behavior: runBlocking bridges blocking code, launch starts work without a returned value, and async computes a value asynchronously. section 14.5.1 section 14.6
Bridge regular code with runBlocking
import kotlinx.coroutines.* import kotlin.time.Duration.Companion.milliseconds suspend fun doSomethingSlowly() { delay(500.milliseconds) println("I'm done") } fun main() = runBlocking { doSomethingSlowly() } Here, runBlocking creates and runs the coroutine, blocks the current thread until completion, and permits the suspending function call inside its body. Although it blocks one thread, child coroutines started with launch can suspend without blocking additional threads. section 14.6.1
Choose a builder according to the coroutine’s role:
- Use runBlocking to bridge blocking code and suspending functions. section 14.6.1
- Use launch to start a coroutine that does not return a value. section 14.6
- Use async to compute a value asynchronously; await rethrows an exception raised during that computation. section 14.6 section 18.1
- Pass a dispatcher such as Dispatchers.Default to a builder when the coroutine should use a specific dispatcher. section 14.7.2
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()
}
Inspect a complete runBlocking example that invokes a suspending function and delays before producing output. section 14.6.1
Listing 14.8 Specifying a dispatcher as a parameter to a coroutine builder
fun main() {
runBlocking {
log("Doing some work")
launch(Dispatchers.Default) { #1
log("Doing some background work")
}
}
}
Inspect a builder configured with Dispatchers.Default and compare the logged execution threads. section 14.7.2
