0
0
Android Kotlinmobile~10 mins

Coroutines for async networking in Android Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
ADefault
BIO
CUnconfined
DMain
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.IO for UI work causes errors.
Forgetting to specify a dispatcher.
2fill in blank
medium

Complete 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'
AMain
BIO
CDefault
DUnconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.Main causes app to freeze.
Using Dispatchers.Default is less efficient for IO.
3fill in blank
hard

Fix 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'
AMain
BIO
CDefault
DUnconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Updating UI on Dispatchers.IO causes crashes.
Not catching exceptions in coroutines.
4fill in blank
hard

Fill 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'
AIO
Blaunch
CMain
Dasync
Attempts:
3 left
💡 Hint
Common Mistakes
Using async when no result is needed.
Using Main dispatcher for network calls.
5fill in blank
hard

Fill 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'
AMain
BIO
Cawait
Dasync
Attempts:
3 left
💡 Hint
Common Mistakes
Calling await() on a non-Deferred object.
Using Main dispatcher for network calls.