0
0
Android Kotlinmobile~10 mins

withContext for thread switching 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 switch to the IO dispatcher using withContext.

Android Kotlin
suspend fun fetchData() {
  withContext([1]) {
    // perform IO operation
  }
}
Drag options to blanks, or click blank then click option'
ADispatchers.Main
BDispatchers.Default
CDispatchers.Unconfined
DDispatchers.IO
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.Main causes UI blocking.
Using Dispatchers.Default is for CPU-intensive tasks, not IO.
2fill in blank
medium

Complete the code to switch back to the Main dispatcher after an IO operation.

Android Kotlin
suspend fun updateUI() {
  withContext(Dispatchers.IO) {
    // fetch data
  }
  withContext([1]) {
    // update UI
  }
}
Drag options to blanks, or click blank then click option'
ADispatchers.IO
BDispatchers.Unconfined
CDispatchers.Main
DDispatchers.Default
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.IO for UI updates causes exceptions.
Using Dispatchers.Default does not guarantee main thread execution.
3fill in blank
hard

Fix the error in the code by choosing the correct dispatcher for CPU-intensive work.

Android Kotlin
suspend fun calculate() {
  withContext([1]) {
    // heavy computation
  }
}
Drag options to blanks, or click blank then click option'
ADispatchers.IO
BDispatchers.Default
CDispatchers.Main
DDispatchers.Unconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.IO for CPU work can cause thread starvation.
Using Dispatchers.Main blocks the UI.
4fill in blank
hard

Fill both blanks to correctly switch context for network call and UI update.

Android Kotlin
suspend fun loadData() {
  withContext([1]) {
    // network call
  }
  withContext([2]) {
    // update UI
  }
}
Drag options to blanks, or click blank then click option'
ADispatchers.IO
BDispatchers.Main
CDispatchers.Default
DDispatchers.Unconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Reversing the dispatchers causes UI crashes or blocking.
Using Dispatchers.Default for network calls is inefficient.
5fill in blank
hard

Fill all three blanks to create a map of word lengths filtering words longer than 4 characters.

Android Kotlin
suspend fun processWords(words: List<String>): Map<String, Int> = withContext([1]) {
  words.associateWith { word -> word.length }
}.filter { (word, length) -> length [2] [3] }
Drag options to blanks, or click blank then click option'
ADispatchers.Default
B>
C4
DDispatchers.IO
Attempts:
3 left
💡 Hint
Common Mistakes
Using IO dispatcher for length calculation is inefficient.
Using wrong comparison operator or number in filter.