CodeBlanks Logo Icon CodeBlanks

async/await

Learn parallel coroutines with async and await.

async and await

async starts a coroutine that returns a result and returns a Deferred<T>. The await() call retrieves the result. Example: val a = async { 10 }; println(a.await()) }.

Multiple async calls start in parallel; each runs in its own coroutine. Even if await() is called sequentially, the total time approaches the longest one because computations run in parallel. This is the difference from launch: launch is resultless, async is resultful. Keep the await order fixed for deterministic output.

async/await parallelism

When two async calls start in parallel each runs concurrently. In val a = async { 10 }; val b = async { 20 } both computations start at once. println(a.await() + b.await()) waits for both and gives the sum.

The output is deterministic: 30. Because await collects results in a fixed order. Parallel execution shortens time but the result values are fixed. async is called only inside a coroutine scope (such as runBlocking).

Practice Sum with async and await

Add import kotlinx.coroutines.*. Write fun main() = runBlocking; inside define val a = async { 10 } and val b = async { 20 }. Print the sum with println(a.await() + b.await()).

Starter code

Main.kt
import kotlinx.coroutines.*

// Start two async calls in runBlocking and sum with await

Sample solution

Main.kt
import kotlinx.coroutines.*

fun main() = runBlocking {
    val a = async { 10 }
    val b = async { 20 }
    println(a.await() + b.await())
}

Expected output

30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the async/await concepts

Term Meaning
async Start with result
await Get result
Deferred Type
parallel Parallel

2 Complete the await call

Question
val a = async { 10 }
val result = a.____()
Answer
val a = async { 10 }
val result = a.await()

Explanation: await retrieves the value from a Deferred.

3 What does async return?

  • Deferred Correct answer
  • Int
  • Unit
  • Job

Explanation: async returns a Deferred<T>; await retrieves the value.

All lessons in Intermediate