We use launch and async builders to run tasks in the background without freezing the app. This helps keep the app smooth and responsive.
launch and async builders in Android Kotlin
launch {
// code to run in background
}
val deferred = async {
// code that returns a result
}
val result = deferred.await()launch runs a task without returning a result.
async runs a task and returns a Deferred result you can wait for with await().
launch {
println("Running in background")
}val deferred = async { 5 + 5 } val result = deferred.await() println(result)
This program runs a background task with launch that prints after 1 second. It also runs an async task that returns 42 after 0.5 seconds. The main function waits for the async result and prints it.
import kotlinx.coroutines.* fun main() = runBlocking { launch { delay(1000L) println("Task from launch") } val deferred = async { delay(500L) 42 } println("Waiting for async result...") val result = deferred.await() println("Result is $result") }
Use launch when you don't need a result back.
Use async when you want to get a result from the background task.
Always call await() on Deferred to get the result and wait for completion.
launch runs background code without returning a value.
async runs background code and returns a result you can wait for.
Both help keep your app smooth by not blocking the main thread.
Practice
launch and async builders in Kotlin coroutines?Solution
Step 1: Understand
launchbehaviorlaunchstarts a coroutine that runs code asynchronously but does not return a value.Step 2: Understand
asyncbehaviorasyncstarts a coroutine and returns aDeferredobject, which you can await to get a result.Final Answer:
launchdoes not return a result,asyncreturns a Deferred result. -> Option DQuick Check:
launch = no result, async = returns result [OK]
- Thinking launch returns a value
- Confusing async with blocking calls
- Assuming launch blocks the main thread
async in Kotlin?Solution
Step 1: Identify correct coroutine builder usage
asyncis called as a function returning a Deferred, soval result = async { fetchData() }is correct.Step 2: Check other options for syntax errors
launchdoes not return a value, so val result = launch { fetchData() } is wrong for async usage. Options C and D have invalid syntax.Final Answer:
val result = async { fetchData() } -> Option CQuick Check:
async returns Deferred, so assign it [OK]
- Using launch instead of async when expecting a result
- Trying to chain async.launch or launch.async
- Not assigning async result to a variable
fun main() = runBlocking {
val deferred = async {
delay(100)
10 + 20
}
println("Result: ${deferred.await()}")
}Solution
Step 1: Understand async and await behavior
Theasyncblock runs asynchronously and returns a Deferred. Callingawait()waits for the result.Step 2: Calculate the expression inside async
The code delays 100ms then returns 10 + 20 = 30, which is printed.Final Answer:
Result: 30 -> Option BQuick Check:
async + await returns computed value [OK]
- Forgetting to call await() to get result
- Expecting immediate result without delay
- Confusing launch with async return
fun main() = runBlocking {
val result = launch {
val data = fetchData()
}
println(data)
}
suspend fun fetchData(): String {
delay(100)
return "Hello"
}Solution
Step 1: Check variable scope of 'data'
The variable 'data' is declared inside the launch coroutine block, so it is not visible outside.Step 2: Analyze println(data) usage
Trying to print 'data' outside launch causes a compilation error because 'data' is undefined there.Final Answer:
Variable 'data' is not accessible outside launch block -> Option AQuick Check:
Variables inside launch are local to its block [OK]
- Assuming launch returns a value
- Trying to await launch (which returns Job)
- Ignoring variable scope rules
val data1 = async { fetchData1() }
val data2 = async { fetchData2() }
val combined = data1.await() + data2.await()
Why is this approach preferred over launching two launch coroutines and combining results later?Solution
Step 1: Understand concurrency with async
Usingasyncstarts coroutines that return Deferred results, allowing you to wait for and combine their outputs.Step 2: Compare with launch behavior
launchreturns Job and does not provide a direct result, so combining outputs requires extra state management.Final Answer:
async returns Deferred results that can be awaited and combined immediately -> Option AQuick Check:
async = awaitable result, launch = no result [OK]
- Thinking launch returns a value
- Assuming launch blocks main thread
- Believing async caches results automatically
Ready to prove it?
Pass the test and this pattern moves unknown
