0
0
Kotlinprogramming~5 mins

Async coroutine builder in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AA Deferred object representing a future result
BA Job object with no result
CA regular function result immediately
DA Thread object
Which function do you call to get the result from an async coroutine?
Astart()
Bjoin()
Cawait()
Drun()
What happens if you call await() on a Deferred that is already completed?
AThrows an exception
BReturns the result immediately without suspension
CSuspends indefinitely
DStarts the coroutine again
Which coroutine builder is best when you want to start a coroutine that does not return a result?
AwithContext
Basync
CrunBlocking
Dlaunch
What is the main advantage of using async over sequential code?
ARuns tasks concurrently to save time
BRuns tasks sequentially to avoid errors
CBlocks the main thread
DRuns tasks on a new thread always
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.