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.
Async and await for concurrent results in 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.
val deferred = async { 5 + 5 } val result = deferred.await() println(result)
val deferred1 = async { fetchDataFromServer1() } val deferred2 = async { fetchDataFromServer2() } val result1 = deferred1.await() val result2 = deferred2.await() println("Results: $result1 and $result2")
This program starts two tasks that finish after different times. It waits for both to finish and then prints their results.
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) }
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.
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.
Practice
async function do in Kotlin coroutines?Solution
Step 1: Understand the role of
asyncasyncstarts a coroutine that runs in the background without blocking the main thread.Step 2: Differentiate from
awaitawaitwaits for the result of the background task started byasync, butasyncitself only starts the task.Final Answer:
Starts a background task that runs concurrently -> Option AQuick Check:
async = starts background task [OK]
- Confusing async with await
- Thinking async blocks the main thread
- Assuming async cancels tasks
Solution
Step 1: Identify correct async-await usage
In Kotlin,asyncreturns a Deferred object, which you then callawait()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 CQuick Check:
async returns Deferred, await gets result [OK]
- Calling await immediately after async (no concurrency)
- Using await as a standalone function
- Not storing async result before await
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred1 = async {
delay(100)
10
}
val deferred2 = async {
delay(50)
20
}
println(deferred1.await() + deferred2.await())
}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 BQuick Check:
10 + 20 = 30 [OK]
- Assuming sequential execution ignoring concurrency
- Confusing delay times with output values
- Expecting compilation errors due to coroutines
fun main() = runBlocking {
val result = async {
delay(100)
42
}.await()
println(result)
}Solution
Step 1: Analyze async and await usage
Callingawait()immediately afterasyncwaits for the task to finish before continuing, so concurrency is lost.Step 2: Understand concurrency impact
This pattern runs the async task sequentially, blocking until completion, defeating the purpose of async concurrency.Final Answer:
Calling await() immediately after async() blocks concurrency -> Option AQuick Check:
Immediate await blocks concurrency [OK]
- Thinking immediate await keeps concurrency
- Believing delay is disallowed inside async
- Assuming runBlocking can't be main
Solution
Step 1: Understand concurrency for API calls
Starting both API calls concurrently withasyncallows them to run at the same time, saving time.Step 2: Await both results before combining
Usingawaiton both deferred results ensures you get both responses before combining them safely.Final Answer:
Start two async coroutines for each API call, then await both results before combining -> Option DQuick Check:
Async start + await both = concurrent fetch [OK]
- Running API calls sequentially losing concurrency
- Using await without async causing errors
- Not awaiting results before combining
Ready to prove it?
Pass the test and this pattern moves unknown
