0
0
Kotlinprogramming~5 mins

Async and await for concurrent results in Kotlin

Choose your learning style9 modes available
Introduction

Async and await let your program do many things at the same time. This helps it run faster by not waiting for one task to finish before starting another.

When you want to download several files from the internet at once.
When you need to get data from multiple sources without waiting for each one in order.
When you want to run several calculations at the same time to save time.
When you want your app to stay responsive while doing slow tasks in the background.
Syntax
Kotlin
val deferred = async {
    // some long running task
}

val result = deferred.await()

async starts a task that runs in the background.

await waits for the task to finish and gets the result.

Examples
This runs a simple addition in the background and prints 10.
Kotlin
val deferred = async {
    5 + 5
}
val result = deferred.await()
println(result)
This runs two data fetches at the same time and waits for both results.
Kotlin
val deferred1 = async { fetchDataFromServer1() }
val deferred2 = async { fetchDataFromServer2() }

val result1 = deferred1.await()
val result2 = deferred2.await()
println("Results: $result1 and $result2")
Sample Program

This program starts two tasks that finish after different times. It waits for both to finish and then prints their results.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred1 = async {
        delay(1000L) // pretend to do some work
        "First Result"
    }
    val deferred2 = async {
        delay(500L) // faster work
        "Second Result"
    }

    println("Waiting for results...")
    val result1 = deferred1.await()
    val result2 = deferred2.await()

    println("Got results:")
    println(result1)
    println(result2)
}
OutputSuccess
Important Notes

Use runBlocking in main to run suspend functions in a simple program.

Async tasks start immediately and run in parallel inside the coroutine scope.

Await pauses only the current coroutine until the result is ready, not the whole program.

Summary

Async starts a background task that runs at the same time as others.

Await waits for the background task to finish and gets its result.

Using async and await together helps your program do many things faster and stay responsive.