await() / Deferred
In Kotlin coroutines, Deferred<T> is an object that holds the result of an asynchronous operation. Calling await() on it suspends the current coroutine until the result is ready.
Syntax
// Get a Deferred using async
val deferred: Deferred<Type> = async {
// Asynchronous operation
result // Return value
}
// Get the result with await (can only be called inside a coroutine)
val result: Type = deferred.await()
// Use awaitAll to wait for multiple Deferreds at once
val results: List<Type> = awaitAll(deferred1, deferred2, deferred3)
Methods and Properties
| Method / Property | Description |
|---|---|
| deferred.await() | Suspends the coroutine until the result is ready, then returns it. |
| awaitAll(vararg deferred) | Waits for multiple Deferreds concurrently and returns a list of results. |
| deferred.isCompleted | Returns whether the operation has completed. |
| deferred.isCancelled | Returns whether the operation has been cancelled. |
| deferred.cancel() | Cancels the asynchronous operation. |
| deferred.getCompleted() | Returns the result if completed; throws an exception if not yet complete. |
Sample Code
import kotlinx.coroutines.*
suspend fun fetchUser(id: Int): String {
delay(200)
return "User-$id"
}
suspend fun fetchScore(id: Int): Int {
delay(150)
return id * 100
}
fun main() = runBlocking {
// Launch two async operations concurrently.
val userDeferred = async { fetchUser(1) }
val scoreDeferred = async { fetchScore(1) }
// Retrieve each result using await.
val user = userDeferred.await()
val score = scoreDeferred.await()
println("$user: $score points") // User-1: 100 points
// Use awaitAll to retrieve multiple results at once.
val deferreds = (1..3).map { id ->
async { fetchUser(id) }
}
val users = awaitAll(*deferreds.toTypedArray())
println(users) // [User-1, User-2, User-3]
// Check completion with isCompleted
val d = async { delay(500); "done" }
println(d.isCompleted) // false (still running)
d.await()
println(d.isCompleted) // true
}
Notes
To run operations in parallel, launch multiple async blocks first and then call await() on each afterward. Calling await() immediately after each async results in sequential execution.
Use awaitAll() to wait for multiple Deferreds together. If any one of them throws an exception, the others are cancelled as well.
For details on how to launch coroutines, see launch / async. For timeouts, see delay() / withTimeout().
If you find any errors or copyright issues, please contact us.