The other main coroutine builder alongside launch is async , which creates a coroutine that returns a computed value. (Recall that launch was used for side effects.) The computed value is wrapped inside a class called Deferred that allows access to the eventual result through an await function that suspends the calling coroutine until the value is available. You can think of deferred as the coroutine equivalent of a regular Future.
A deferred coroutine is a subclass of Job, so all the functions on job apply to deferred as well.
Let's look at async in action:
fun main() {
runBlocking {
val deferred = async {
println("Computing value...")
delay(1000)
"result"
}
val result = deferred.await()
println("The result is $result")
}
}
Running this example, outputs the following:
Computing value......
The result is result