0
0
Kotlinprogramming~10 mins

Dispatchers.Main, IO, Default behavior in 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 on the main thread.

Kotlin
CoroutineScope(Dispatchers.[1]).launch {
    // UI update code here
}
Drag options to blanks, or click blank then click option'
AMain
BDefault
CUnconfined
DIO
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.IO for UI updates causes errors because it's for background work.
Using Dispatchers.Default does not guarantee running on the main thread.
2fill in blank
medium

Complete the code to perform a network request on the appropriate dispatcher.

Kotlin
CoroutineScope(Dispatchers.[1]).launch {
    val data = fetchData()
    // process data
}
Drag options to blanks, or click blank then click option'
AIO
BMain
CDefault
DUnconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.Main for network calls can freeze the UI.
Dispatchers.Default is for CPU-intensive tasks, not IO.
3fill in blank
hard

Fix the error in the code to run a CPU-intensive task on the correct dispatcher.

Kotlin
CoroutineScope(Dispatchers.[1]).launch {
    val result = heavyComputation()
    // use result
}
Drag options to blanks, or click blank then click option'
AMain
BDefault
CIO
DUnconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.IO for CPU tasks can cause thread starvation.
Using Dispatchers.Main for heavy work blocks the UI.
4fill in blank
hard

Fill both blanks to create a coroutine that switches from IO to Main dispatcher.

Kotlin
CoroutineScope(Dispatchers.[1]).launch {
    val data = fetchData()
    withContext(Dispatchers.[2]) {
        updateUI(data)
    }
}
Drag options to blanks, or click blank then click option'
AIO
BMain
CDefault
DUnconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Not switching back to Main dispatcher before UI update.
Using Default dispatcher for IO tasks.
5fill in blank
hard

Fill all three blanks to create a coroutine that performs CPU work, then IO, then updates UI.

Kotlin
CoroutineScope(Dispatchers.[1]).launch {
    val cpuResult = heavyComputation()
    val ioResult = withContext(Dispatchers.[2]) {
        fetchData()
    }
    withContext(Dispatchers.[3]) {
        updateUI(cpuResult, ioResult)
    }
}
Drag options to blanks, or click blank then click option'
ADefault
BIO
CMain
DUnconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Main dispatcher for CPU or IO tasks.
Not switching dispatchers properly causing UI freezes.