How to Use Async in Kotlin: Simple Guide with Examples
async inside a coroutineScope or runBlocking to start asynchronous tasks that return a Deferred result. You then call await() on the Deferred to get the result without blocking the main thread.Syntax
The async function starts a new coroutine and returns a Deferred object, which is a promise for a future result. You use await() on this object to get the result once it's ready.
It must be called inside a coroutine scope like runBlocking or coroutineScope.
- async { ... }: Starts async task
- Deferred<T>: Holds future result
- await(): Suspends until result is ready
import kotlinx.coroutines.* fun main() = runBlocking { val deferred: Deferred<Int> = async { // Some long running task 42 } val result = deferred.await() println("Result: $result") }
Example
This example shows two async tasks running in parallel. Both tasks delay for some time, then return a value. The await() calls get their results without blocking the main thread.
import kotlinx.coroutines.* fun main() = runBlocking { val deferred1 = async { delay(1000L) // Simulate work "Hello" } val deferred2 = async { delay(500L) // Simulate work "World" } // Await both results val result = "${deferred1.await()} ${deferred2.await()}!" println(result) }
Common Pitfalls
One common mistake is calling async outside a coroutine scope, which causes a compile error. Another is forgetting to call await(), which means the async task runs but you never get its result.
Also, using async without await() does not block the main thread but may cause your program to exit before the async work finishes.
import kotlinx.coroutines.* fun main() { // Wrong: async called outside coroutine scope // val deferred = runBlocking { async { 42 } } // This will compile but is not recommended runBlocking { // Right: async inside coroutine scope val deferred = async { 42 } println(deferred.await()) } }
Quick Reference
| Keyword | Description |
|---|---|
| async { ... } | Starts an asynchronous coroutine and returns a Deferred result |
| Deferred | A promise for a future result of type T |
| await() | Suspends coroutine until Deferred result is ready |
| runBlocking { ... } | Creates a coroutine scope that blocks the current thread |
| coroutineScope { ... } | Creates a coroutine scope that suspends until all child coroutines complete |