📖 Scenario: You are building a simple Kotlin program that fetches two pieces of information at the same time, like ordering coffee and a sandwich together instead of waiting for one before starting the other.
🎯 Goal: Learn how to use async and await in Kotlin to run two tasks concurrently and get their results.
📋 What You'll Learn
Create two suspend functions that simulate fetching data with delays
Use async to start both tasks concurrently
Use await to get the results from both tasks
Print the combined result
💡 Why This Matters
🌍 Real World
Many apps need to do several things at once, like loading images and text together. Using async and await helps make apps faster and smoother.
💼 Career
Understanding async programming is important for Kotlin developers working on Android apps or backend services where multiple tasks run concurrently.
Progress0 / 4 steps
1
Create suspend functions to simulate data fetching
Write two suspend functions called fetchCoffee() and fetchSandwich(). Each should delay for 1000 milliseconds and then return the strings "Coffee" and "Sandwich" respectively.
Kotlin
Hint
Use suspend fun to create functions that can pause. Use delay(1000L) to wait 1 second.
2
Set up the main function with coroutine scope
Create a main function with runBlocking to start a coroutine scope. Inside it, declare two variables coffeeDeferred and sandwichDeferred that use async to call fetchCoffee() and fetchSandwich() concurrently.
Kotlin
Hint
Use runBlocking to create a coroutine scope in main. Use async to start tasks concurrently.
3
Await results from async tasks
Inside the main function, after starting the async tasks, create two variables coffee and sandwich that use await() on coffeeDeferred and sandwichDeferred to get the results.
Kotlin
Hint
Use await() on the deferred variables to get the actual results.
4
Print the combined result
Add a println statement inside main to print the string "Order ready: Coffee and Sandwich" using the variables coffee and sandwich with an f-string style template.
Kotlin
Hint
Use println("Order ready: $coffee and $sandwich") to show the final message.
Practice
(1/5)
1. What does the async function do in Kotlin coroutines?
easy
A. Starts a background task that runs concurrently
B. Waits for a task to complete and returns its result
C. Blocks the main thread until a task finishes
D. Cancels a running coroutine immediately
Solution
Step 1: Understand the role of async
async starts a coroutine that runs in the background without blocking the main thread.
Step 2: Differentiate from await
await waits for the result of the background task started by async, but async itself only starts the task.
Final Answer:
Starts a background task that runs concurrently -> Option A
Quick Check:
async = starts background task [OK]
Hint: Async starts tasks without waiting, await waits for results [OK]
Common Mistakes:
Confusing async with await
Thinking async blocks the main thread
Assuming async cancels tasks
2. Which of the following is the correct syntax to start two concurrent tasks and wait for both results in Kotlin?
easy
A. val result1 = async { task1() }.await()
val result2 = async { task2() }.await()
B. val result1 = await(async { task1() })
val result2 = await(async { task2() })
C. val deferred1 = async { task1() }
val deferred2 = async { task2() }
val result1 = deferred1.await()
val result2 = deferred2.await()
D. val result1 = task1()
val result2 = task2()
Solution
Step 1: Identify correct async-await usage
In Kotlin, async returns a Deferred object, which you then call await() on to get the result.
Step 2: Check syntax correctness
val deferred1 = async { task1() }
val deferred2 = async { task2() }
val result1 = deferred1.await()
val result2 = deferred2.await() correctly starts two async tasks and awaits their results separately, allowing concurrency.
Final Answer:
val deferred1 = async { task1() }
val deferred2 = async { task2() }
val result1 = deferred1.await()
val result2 = deferred2.await() -> Option C
Quick Check:
async returns Deferred, await gets result [OK]
Hint: Store async in Deferred, then call await separately [OK]
Common Mistakes:
Calling await immediately after async (no concurrency)
Using await as a standalone function
Not storing async result before await
3. What will be the output of the following Kotlin code?
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred1 = async {
delay(100)
10
}
val deferred2 = async {
delay(50)
20
}
println(deferred1.await() + deferred2.await())
}
medium
A. 10
B. 30
C. 20
D. Compilation error
Solution
Step 1: Understand async and delay behavior
Two async tasks run concurrently: one delays 100ms and returns 10, the other delays 50ms and returns 20.
Step 2: Await both results and sum
Awaiting both deferreds gets 10 and 20, summing to 30, printed as output.
Final Answer:
30 -> Option B
Quick Check:
10 + 20 = 30 [OK]
Hint: Sum awaited results after async tasks complete [OK]