0
0
KotlinHow-ToBeginner · 4 min read

How to Use Async in Kotlin: Simple Guide with Examples

In Kotlin, you use 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
kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred: Deferred<Int> = async {
        // Some long running task
        42
    }
    val result = deferred.await()
    println("Result: $result")
}
Output
Result: 42
💻

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.

kotlin
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)
}
Output
Hello World!
⚠️

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.

kotlin
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())
    }
}
Output
42
📊

Quick Reference

KeywordDescription
async { ... }Starts an asynchronous coroutine and returns a Deferred result
DeferredA 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

Key Takeaways

Use async inside a coroutine scope like runBlocking or coroutineScope.
async returns a Deferred object; call await() to get the result.
async allows running tasks concurrently without blocking the main thread.
Always await Deferred results to avoid unfinished work or lost results.
Calling async outside a coroutine scope causes errors.