Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to launch a coroutine in the main thread.
Android Kotlin
GlobalScope.launch(Dispatchers.[1]) {
// network call here
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.IO for UI work causes errors.
Forgetting to specify a dispatcher.
✗ Incorrect
Use Dispatchers.Main to run coroutines on the main thread, suitable for UI updates.
2fill in blank
mediumComplete the code to make a network call asynchronously using suspend function.
Android Kotlin
suspend fun fetchData() : String {
return withContext(Dispatchers.[1]) {
// simulate network call
"data"
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.Main causes app to freeze.
Using Dispatchers.Default is less efficient for IO.
✗ Incorrect
Use Dispatchers.IO for blocking IO tasks like network calls to avoid blocking the main thread.
3fill in blank
hardFix the error in the coroutine builder to properly handle exceptions.
Android Kotlin
GlobalScope.launch(Dispatchers.IO) {
try {
val result = fetchData()
withContext(Dispatchers.[1]) {
// update UI with result
}
} catch (e: Exception) {
// handle error
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Updating UI on Dispatchers.IO causes crashes.
Not catching exceptions in coroutines.
✗ Incorrect
UI updates must happen on the main thread, so use Dispatchers.Main inside withContext.
4fill in blank
hardFill both blanks to create a coroutine scope and launch a coroutine for network call.
Android Kotlin
val scope = CoroutineScope(Dispatchers.[1] + Job()) scope.[2] { val data = fetchData() // process data }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using async when no result is needed.
Using Main dispatcher for network calls.
✗ Incorrect
Use Dispatchers.IO for network calls and launch to start a coroutine without returning a result.
5fill in blank
hardFill all three blanks to create an async coroutine that fetches data and awaits the result.
Android Kotlin
val deferred = CoroutineScope(Dispatchers.[1]).[2] { fetchData() } val result = deferred.[3]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling await() on a non-Deferred object.
Using Main dispatcher for network calls.
✗ Incorrect
Use Dispatchers.IO for network, async to start coroutine returning Deferred, and await to get result.