Kotlin Async and Await
async starts a coroutine that produces a value, and the value is held in a Deferred. await pauses until that value is ready and then returns it.
One async value
async starts a block that produces 20, and the result is stored as a Deferred of Int. await returns that value, and the print shows it.
import kotlinx.coroutines.*
fun main() {
runBlocking {
val result: Deferred<Int> = async {
20
}
println(result.await())
}
}Two values awaited in a fixed order
Both async blocks start before any await call. The awaits run first and then second, so the prints land in that order.
import kotlinx.coroutines.*
fun main() {
runBlocking {
val first = async {
20
}
val second = async {
22
}
println("First: ${first.await()}")
println("Second: ${second.await()}")
}
}Awaiting the same Deferred twice
The block produces its value once. Both await calls return that same value, so the number prints twice.
import kotlinx.coroutines.*
fun main() {
runBlocking {
val value = async {
7
}
println(value.await())
println(value.await())
}
}Two async strings joined
Each async block produces one string. The awaits run in written order, and the two results join into one greeting.
import kotlinx.coroutines.*
fun main() {
runBlocking {
val greeting = async {
"Hello"
}
val name = async {
"Ana"
}
println(greeting.await() + ", " + name.await())
}
}Example
import kotlinx.coroutines.*
fun main() {
runBlocking {
val first = async {
30
}
val second = async {
12
}
val firstValue = first.await()
val secondValue = second.await()
println("First: $firstValue")
println("Second: $secondValue")
println("Total: ${firstValue + secondValue}")
}
}Key points
- async starts its block as a coroutine and returns a Deferred for the value the block produces.
- A Deferred is a handle for a result that is not ready yet.
- await is called on a Deferred, and it returns the value once the value is ready.
- Awaiting the same Deferred twice returns the same value both times.
- Two async blocks can be started first and awaited later in a chosen order.
In this example, two async blocks produce 30 and 12. The awaits collect the first value and then the second value, in that order. The prints show each value and then their total of 42.
Note
The printed order in these examples follows the await order, not a finishing order.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What happens when the same Deferred is awaited twice?