0
0
Kotlinprogramming~10 mins

Coroutine context and dispatchers 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 IO dispatcher.

Kotlin
GlobalScope.launch([1]) {
    println("Running in IO dispatcher")
}
Drag options to blanks, or click blank then click option'
ADispatchers.Default
BDispatchers.Main
CDispatchers.IO
DDispatchers.Unconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.Main for IO tasks causes blocking on the main thread.
Using Dispatchers.Default is for CPU-intensive tasks, not IO.
2fill in blank
medium

Complete the code to switch the coroutine context to the Default dispatcher.

Kotlin
withContext([1]) {
    println("Running in Default dispatcher")
}
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 tasks is inefficient.
Dispatchers.Main is for UI thread, not CPU work.
3fill in blank
hard

Fix the error in the coroutine builder to use the correct dispatcher for UI updates.

Kotlin
GlobalScope.launch([1]) {
    // Update UI here
    println("Updating UI")
}
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.IO or Default causes exceptions when updating UI.
Unconfined dispatcher may run on any thread, unsafe for UI.
4fill in blank
hard

Fill both blanks to create a coroutine context combining a Job and the Default dispatcher.

Kotlin
val job = Job()
val context = job + [1]

GlobalScope.launch(context) {
    println("Running with combined context")
}
Drag options to blanks, or click blank then click option'
ADispatchers.Default
BDispatchers.IO
CDispatchers.Main
DDispatchers.Unconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.IO here is for IO, not CPU work.
Dispatchers.Main is for UI, not combined with Job for CPU tasks.
5fill in blank
hard

Fill all three blanks to create a coroutine that runs on the IO dispatcher, with a SupervisorJob and a custom CoroutineName.

Kotlin
val supervisor = [1]()
val context = supervisor + [2] + [3]("MyCoroutine")

GlobalScope.launch(context) {
    println("Running supervised coroutine with name")
}
Drag options to blanks, or click blank then click option'
AJob
BDispatchers.IO
CCoroutineName
DSupervisorJob
Attempts:
3 left
💡 Hint
Common Mistakes
Using Job instead of SupervisorJob loses supervision benefits.
Using Dispatchers.Default instead of IO changes the thread pool.
Forgetting CoroutineName loses coroutine identification.