0
0
Kotlinprogramming~10 mins

Async and await for concurrent results in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Async and await for concurrent results
Start main coroutine
Launch async tasks
Tasks run concurrently
Await results
Combine results
Print or return combined result
End
Start a coroutine, launch async tasks that run at the same time, wait for their results, then combine and use those results.
Execution Sample
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
  val deferred1 = async { delay(1000); 10 }
  val deferred2 = async { delay(500); 20 }
  val result = deferred1.await() + deferred2.await()
  println("Result: $result")
}
Runs two async tasks concurrently, waits for both, then prints their sum.
Execution Table
StepActionTask1 StateTask2 StateResult VariableOutput
1Start runBlocking main coroutineNot startedNot startedN/AN/A
2Launch async task1 (delay 1000ms, returns 10)Running (delay)Not startedN/AN/A
3Launch async task2 (delay 500ms, returns 20)Running (delay)Running (delay)N/AN/A
4Await deferred2 (task2 finishes after 500ms)Running (delay)Completed (20)N/AN/A
5Await deferred1 (task1 finishes after 1000ms)Completed (10)Completed (20)N/AN/A
6Calculate result = 10 + 20Completed (10)Completed (20)30N/A
7Print resultCompleted (10)Completed (20)30Result: 30
8End runBlocking coroutineCompleted (10)Completed (20)30N/A
💡 Both async tasks complete, results awaited, sum calculated and printed.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6Final
deferred1nullRunning (delay)Running (delay)Running (delay)Completed (10)Completed (10)Completed (10)
deferred2nullNot startedRunning (delay)Completed (20)Completed (20)Completed (20)Completed (20)
resultN/AN/AN/AN/AN/A3030
Key Moments - 3 Insights
Why do both async tasks run at the same time instead of one after the other?
Because async launches tasks concurrently without waiting, as shown in steps 2 and 3 where both tasks start before awaiting results.
What happens if we await deferred1 before deferred2?
Awaiting deferred1 first would wait for the longer task to finish before checking deferred2, delaying the total time. The execution_table shows awaiting deferred2 first lets us get its result earlier.
Why do we need to call await() on deferred results?
Await suspends the coroutine until the async task finishes and returns its value, as seen in steps 4 and 5 where await gets the completed results.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the state of deferred2 after step 4?
ANot started
BCompleted with value 20
CRunning (delay)
DCancelled
💡 Hint
Check the 'Task2 State' column at step 4 in the execution_table.
At which step does the result variable get its final value?
AStep 6
BStep 4
CStep 5
DStep 7
💡 Hint
Look at the 'Result Variable' column in the execution_table.
If deferred2 took longer than deferred1, how would the execution_table change?
Aresult would be calculated before any await
Bdeferred1 would never complete
Cdeferred2 would complete after deferred1, changing steps 4 and 5 states
DNo change at all
💡 Hint
Consider the timing of task completions in the 'Task1 State' and 'Task2 State' columns.
Concept Snapshot
Use async to start tasks concurrently.
Use await to wait for each task's result.
Tasks run at the same time, saving time.
Combine awaited results after all finish.
runBlocking starts the main coroutine.
Delays simulate work in async blocks.
Full Transcript
This example shows how Kotlin coroutines use async and await to run tasks at the same time and wait for their results. First, the main coroutine starts with runBlocking. Then two async tasks launch: one delays 1000ms and returns 10, the other delays 500ms and returns 20. Both run concurrently. Await suspends until each task finishes, first deferred2 after 500ms, then deferred1 after 1000ms. After both complete, their results are added and printed. This saves time compared to running tasks one after another. The execution table tracks each step, showing task states and when results are ready. The variable tracker shows how deferred1, deferred2, and result change over time. Key moments clarify why async runs tasks together, why await is needed, and how order of awaiting affects timing. The quiz tests understanding of task states and result timing. The snapshot summarizes the main points for quick review.