Bird
Raised Fist0
Kotlinprogramming~10 mins

Async coroutine builder in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Async coroutine builder
Start main coroutine
↓
Call async builder
↓
Launch child coroutine
↓
Child does work asynchronously
↓
Child returns Deferred result
↓
Main awaits result
↓
Result received
↓
Continue main coroutine
The async builder launches a child coroutine that runs concurrently and returns a Deferred result, which the main coroutine can await.
Execution Sample
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
  val deferred = async {
    delay(1000L)
    42
  }
  println("Waiting for result...")
  println("Result: ${deferred.await()}")
}
This code runs an async coroutine that waits 1 second and returns 42, which the main coroutine awaits and prints.
Execution Table
StepActionCoroutineStateOutput
1runBlocking starts main coroutinemainRunning
2async builder calledmainRunning
3async launches child coroutinechildRunning
4child coroutine delays 1000mschildSuspended
5main prints waiting messagemainRunningWaiting for result...
6main awaits deferred resultmainSuspended
7child coroutine resumes after delaychildRunning
8child coroutine returns 42childCompleted
9main resumes with result 42mainRunningResult: 42
10main coroutine completesmainCompleted
💡 Main coroutine completes after receiving and printing the async result.
Variable Tracker
VariableStartAfter Step 2After Step 8After Step 9Final
deferrednullDeferred(pending)Deferred(completed with 42)Deferred(completed with 42)Deferred(completed with 42)
Key Moments - 3 Insights
Why does the main coroutine print "Waiting for result..." before the async coroutine finishes?
Because async launches the child coroutine concurrently and immediately returns a Deferred, so the main coroutine continues running and prints before awaiting the result (see step 5 in execution_table).
What happens when main calls deferred.await()?
If the async coroutine is still running, main suspends until the result is ready. In this example, main suspends at step 6 and resumes at step 9 when the child returns 42.
Is the async coroutine blocking the main thread?
No, async runs the child coroutine concurrently without blocking. The main coroutine can do other work or suspend while waiting for the result.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of the child coroutine at step 4?
ARunning
BSuspended
CCompleted
DNot started
💡 Hint
Check the 'State' column for step 4 in the execution_table.
At which step does the main coroutine resume after awaiting the async result?
AStep 5
BStep 7
CStep 9
DStep 10
💡 Hint
Look for when main prints the result after await in the execution_table.
If the delay in async was removed, how would the output change?
AMain would print "Result: 42" immediately after "Waiting for result..."
BMain would print "Waiting for result..." after the result
CMain would never print "Waiting for result..."
DMain would suspend indefinitely
💡 Hint
Without delay, async completes immediately, so await returns instantly (see variable_tracker and execution_table).
Concept Snapshot
async { ... } launches a child coroutine concurrently
Returns Deferred<T> which holds the future result
Use await() on Deferred to suspend until result is ready
Main coroutine continues running until await
Allows non-blocking asynchronous code
Full Transcript
This example shows how Kotlin's async coroutine builder works. The main coroutine starts and calls async, which launches a child coroutine that delays for 1 second and then returns 42. Meanwhile, the main coroutine prints a waiting message and then calls await on the Deferred result. If the child coroutine is still running, main suspends until the result is ready. When the child finishes, main resumes and prints the result. This allows asynchronous work without blocking the main thread.

Practice

(1/5)
1. What does the async coroutine builder do in Kotlin?
easy
A. Starts a background task and returns a Deferred result
B. Blocks the main thread until the task finishes
C. Runs code only on the main thread
D. Creates a new thread without coroutine support

Solution

  1. Step 1: Understand async behavior

    The async builder starts a coroutine that runs in the background without blocking the main thread.
  2. Step 2: Recognize the return type

    It returns a Deferred object which holds the future result of the background task.
  3. Final Answer:

    Starts a background task and returns a Deferred result -> Option A
  4. Quick Check:

    async = background task + Deferred [OK]
Hint: async always returns Deferred for background work [OK]
Common Mistakes:
  • Thinking async blocks the main thread
  • Confusing async with launch which returns Job
  • Assuming async runs only on main thread
2. Which of the following is the correct syntax to start an async coroutine in Kotlin?
easy
A. val result = async(compute())
B. val result = async { compute() }
C. val result = async.compute()
D. val result = async -> compute()

Solution

  1. Step 1: Identify correct async syntax

    The async builder is called with a lambda block: async { ... }.
  2. Step 2: Check each option

    val result = async { compute() } correctly uses async { compute() }. Options B, C, and D misuse parentheses or operators.
  3. Final Answer:

    val result = async { compute() } -> Option B
  4. Quick Check:

    async uses curly braces for lambda [OK]
Hint: async always uses curly braces for its block [OK]
Common Mistakes:
  • Using parentheses instead of curly braces
  • Trying to call async like a function with dot notation
  • Using arrow syntax incorrectly
3. What will be the output of this Kotlin code snippet?
import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred = async {
        delay(100)
        42
    }
    println("Result: ${deferred.await()}")
}
medium
A. Result: null
B. Result: Deferred@someHashCode
C. Result: 42
D. Compilation error

Solution

  1. Step 1: Understand async and await

    The async block runs a coroutine that delays 100ms then returns 42. The await() waits for this result.
  2. Step 2: Print the awaited result

    The println prints "Result: " plus the awaited value 42.
  3. Final Answer:

    Result: 42 -> Option C
  4. Quick Check:

    await() returns 42 after delay [OK]
Hint: await() gets the actual result from Deferred [OK]
Common Mistakes:
  • Printing Deferred object instead of awaited value
  • Forgetting to call await()
  • Expecting immediate result without delay
4. Identify the error in this Kotlin coroutine code:
fun main() = runBlocking {
    val deferred = async {
        delay(100)
        10 / 0
    }
    println(deferred.await())
}
medium
A. Division by zero causes ArithmeticException at await()
B. async cannot be used inside runBlocking
C. Missing launch builder for coroutine
D. delay() cannot be called inside async

Solution

  1. Step 1: Analyze the async block

    The async block performs 10 / 0, which causes a division by zero error.
  2. Step 2: Understand exception propagation

    The exception is thrown when await() is called, as it waits for the async result.
  3. Final Answer:

    Division by zero causes ArithmeticException at await() -> Option A
  4. Quick Check:

    Exceptions in async appear on await() [OK]
Hint: Errors inside async show up when calling await() [OK]
Common Mistakes:
  • Thinking async can't be inside runBlocking
  • Assuming delay() is invalid in async
  • Ignoring exceptions thrown inside async block
5. You want to run two independent background tasks concurrently and get their sum. Which Kotlin code correctly uses async to achieve this?
fun main() = runBlocking {
    val deferred1 = async { 10 }
    val deferred2 = async { 20 }
    val sum = ???
    println(sum)
}
hard
A. val sum = deferred1.get() + deferred2.get()
B. val sum = deferred1 + deferred2
C. val sum = await(deferred1) + await(deferred2)
D. val sum = deferred1.await() + deferred2.await()

Solution

  1. Step 1: Understand how to get results from Deferred

    Each async returns a Deferred. To get the actual value, call await() on each.
  2. Step 2: Sum the awaited results

    Use deferred1.await() + deferred2.await() to get the sum of both results.
  3. Final Answer:

    val sum = deferred1.await() + deferred2.await() -> Option D
  4. Quick Check:

    Sum = await both Deferreds [OK]
Hint: Use await() on Deferred to get values before summing [OK]
Common Mistakes:
  • Trying to add Deferred objects directly
  • Using non-existent get() method
  • Calling await() as a standalone function
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard