Recall & Review
beginner
What is the purpose of the
async coroutine builder in Kotlin?The
async builder starts a coroutine that runs concurrently and returns a Deferred object, which represents a future result that can be awaited.Click to reveal answer
beginner
How do you get the result from an
async coroutine?You call the
await() function on the Deferred object returned by async. This suspends the coroutine until the result is ready.Click to reveal answer
intermediate
What is the difference between
launch and async coroutine builders?launch starts a coroutine that does not return a result and is used for jobs. async starts a coroutine that returns a result wrapped in a Deferred.Click to reveal answer
intermediate
Can you explain what happens if you call
await() on a Deferred that is not yet completed?The coroutine calling
await() suspends and waits until the Deferred completes and the result is available.Click to reveal answer
beginner
Show a simple Kotlin code snippet using
async to run two tasks concurrently and get their results.import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred1 = async { 10 * 2 }
val deferred2 = async { 5 + 5 }
println("Result 1: ${deferred1.await()}")
println("Result 2: ${deferred2.await()}")
}Click to reveal answer
What does the
async coroutine builder return?✗ Incorrect
async returns a Deferred which holds a future result that can be awaited.Which function do you call to get the result from an
async coroutine?✗ Incorrect
await() suspends until the Deferred completes and returns the result.What happens if you call
await() on a Deferred that is already completed?✗ Incorrect
If the
Deferred is completed, await() returns the result immediately.Which coroutine builder is best when you want to start a coroutine that does not return a result?
✗ Incorrect
launch is used for coroutines that do not return a result.What is the main advantage of using
async over sequential code?✗ Incorrect
async allows running multiple tasks at the same time, improving efficiency.Explain how the
async coroutine builder works and how you retrieve its result.Think about how you ask a friend to do a task and wait for their answer later.
You got /4 concepts.
Describe the difference between
launch and async coroutine builders in Kotlin.One is for jobs without results, the other for tasks that produce results.
You got /5 concepts.