0
0
Android Kotlinmobile~10 mins

CoroutineScope and dispatchers 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 dispatcher.

Android Kotlin
CoroutineScope(Dispatchers.[1]).launch {
    // UI update code here
}
Drag options to blanks, or click blank then click option'
ADefault
BIO
CMain
DUnconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.IO for UI updates causes errors.
2fill in blank
medium

Complete the code to switch context to a background thread for heavy work.

Android Kotlin
withContext(Dispatchers.[1]) {
    // heavy computation
}
Drag options to blanks, or click blank then click option'
AMain
BDefault
CUnconfined
DIO
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.Main blocks UI thread.
3fill in blank
hard

Fix the error in the coroutine scope declaration to use the IO dispatcher.

Android Kotlin
val scope = CoroutineScope(Dispatchers.[1])
Drag options to blanks, or click blank then click option'
AIO
BDefault
CMain
DUnconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.Main for IO causes blocking UI.
4fill in blank
hard

Fill both blanks to create a CoroutineScope with a Job and the Default dispatcher.

Android Kotlin
val job = Job()
val scope = CoroutineScope(job + Dispatchers.[1])
scope.launch {
    // work
}
job.[2]()
Drag options to blanks, or click blank then click option'
ADefault
Bcancel
CMain
Dstart
Attempts:
3 left
💡 Hint
Common Mistakes
Using start() instead of cancel() on Job.
5fill in blank
hard

Fill all three blanks to launch a coroutine on the IO dispatcher and switch to Main for UI update.

Android Kotlin
CoroutineScope(Dispatchers.[1]).launch {
    val data = fetchData()
    withContext(Dispatchers.[2]) {
        updateUI(data)
    }
}
fun fetchData() = "Data"
fun updateUI(data: String) {
    println("UI updated with $[3]")
}
Drag options to blanks, or click blank then click option'
AMain
BIO
Cdata
DDefault
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up dispatchers or printing wrong variable.