Coroutine builders are extension functions of the CoroutineScope class that can be used to launch coroutines with different characteristics. If we look back at our working example, we can see an example of the launch() builder:
fun main() {
GlobalScope.launch {
delay(500)
println("Coroutines")
}
println("Hello")
Thread.sleep(1000)
}
By calling launch(), we can start a new coroutine without blocking the current thread. There are a variety of other coroutine builders available to us, including the following:
- async: Creates a coroutine and returns a future result as deferred
- produce: Creates a coroutine that returns a stream of values via ReceiveChannel
- broadcast: Creates a coroutine that returns a stream of values via BroadcastChannel
- runBlocking: Runs a new coroutine and blocks the current thread until it returns
By using launch() and other builders, we can control how we want to interact with the results of our coroutines.