Bird
Raised Fist0
Android Kotlinmobile~20 mins

CoroutineScope and dispatchers in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Coroutine Dispatcher Demo
This screen demonstrates launching coroutines with different dispatchers to show how tasks run on various threads.
Target UI
-------------------------
| Coroutine Dispatcher Demo |
|-------------------------|
| [Start IO Task]          |
| [Start Default Task]     |
| [Start Main Task]        |
|                         |
| Logs:                   |
| >                       |
| >                       |
| >                       |
-------------------------
Add three buttons labeled 'Start IO Task', 'Start Default Task', and 'Start Main Task'.
When a button is tapped, launch a coroutine using the corresponding dispatcher: IO, Default, or Main.
Each coroutine should append a log message to a scrollable text area showing the dispatcher used and the thread name.
Ensure UI updates happen on the main thread.
Use CoroutineScope tied to the lifecycle of the screen.
Starter Code
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      CoroutineDispatcherDemo()
    }
  }
}

@Composable
fun CoroutineDispatcherDemo() {
  // TODO: Add state for logs
  // TODO: Add CoroutineScope
  // TODO: Add UI with three buttons and a scrollable text area
  // TODO: Launch coroutines with appropriate dispatchers on button clicks
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      CoroutineDispatcherDemo()
    }
  }
}

@Composable
fun CoroutineDispatcherDemo() {
  val logs = remember { mutableStateListOf<String>() }
  val scope = rememberCoroutineScope()
  val scrollState = rememberScrollState()

  fun logMessage(dispatcherName: String) {
    val threadName = Thread.currentThread().name
    logs.add("Running on $dispatcherName dispatcher, thread: $threadName")
  }

  Column(modifier = Modifier.fillMaxWidth()) {
    Button(onClick = {
      scope.launch(Dispatchers.IO) {
        logMessage("IO")
      }
    }, modifier = Modifier.fillMaxWidth()) {
      Text("Start IO Task")
    }
    Button(onClick = {
      scope.launch(Dispatchers.Default) {
        logMessage("Default")
      }
    }, modifier = Modifier.fillMaxWidth()) {
      Text("Start Default Task")
    }
    Button(onClick = {
      scope.launch(Dispatchers.Main) {
        logMessage("Main")
      }
    }, modifier = Modifier.fillMaxWidth()) {
      Text("Start Main Task")
    }
    Column(modifier = Modifier
      .weight(1f, fill = false)
      .verticalScroll(scrollState)) {
      for (log in logs) {
        Text(log)
      }
    }
  }
}

This solution uses rememberCoroutineScope() to get a scope tied to the composable lifecycle. Three buttons launch coroutines on different dispatchers: Dispatchers.IO for IO tasks, Dispatchers.Default for CPU-intensive tasks, and Dispatchers.Main for UI thread tasks.

Each coroutine appends a log message with the dispatcher name and current thread name to a mutableStateListOf, which updates the UI automatically. The logs are shown in a scrollable column so the user can see all messages.

This demonstrates how coroutines run on different threads depending on the dispatcher, and how to update UI safely from coroutines.

Final Result
Completed Screen
-------------------------
| Coroutine Dispatcher Demo |
|-------------------------|
| [Start IO Task]          |
| [Start Default Task]     |
| [Start Main Task]        |
|                         |
| Logs:                   |
| > Running on IO dispatcher, thread: DefaultDispatcher-worker-1 |
| > Running on Default dispatcher, thread: DefaultDispatcher-worker-2 |
| > Running on Main dispatcher, thread: main                    |
-------------------------
Tapping 'Start IO Task' launches a coroutine on IO dispatcher and logs the thread name.
Tapping 'Start Default Task' launches a coroutine on Default dispatcher and logs the thread name.
Tapping 'Start Main Task' launches a coroutine on Main dispatcher and logs the thread name.
Logs appear below buttons and update automatically.
Stretch Goal
Add a Clear Logs button to remove all log messages.
💡 Hint
Add a button that clears the mutableStateListOf logs when clicked.

Practice

(1/5)
1. What is the main role of CoroutineScope in Kotlin coroutines?
easy
A. It pauses the coroutine execution.
B. It decides which thread the coroutine runs on.
C. It controls the lifecycle and context where coroutines run.
D. It cancels all running threads in the app.

Solution

  1. Step 1: Understand CoroutineScope purpose

    CoroutineScope defines the lifecycle and context for coroutines, managing their start and cancellation.
  2. Step 2: Differentiate from Dispatchers

    Dispatchers decide the thread, but CoroutineScope manages the coroutine's lifecycle and context.
  3. Final Answer:

    It controls the lifecycle and context where coroutines run. -> Option C
  4. Quick Check:

    CoroutineScope = lifecycle control [OK]
Hint: CoroutineScope manages lifecycle, not threads [OK]
Common Mistakes:
  • Confusing CoroutineScope with Dispatchers
  • Thinking CoroutineScope controls threads
  • Assuming CoroutineScope pauses coroutines
2. Which of the following is the correct way to launch a coroutine on the main thread using CoroutineScope and Dispatchers?
easy
A. CoroutineScope(Dispatchers.IO).launch { /* code */ }
B. CoroutineScope(Dispatchers.Main).launch { /* code */ }
C. CoroutineScope(Dispatchers.Default).launch { /* code */ }
D. CoroutineScope(Dispatchers.Unconfined).launch { /* code */ }

Solution

  1. Step 1: Identify dispatcher for main thread

    Dispatchers.Main is used to run coroutines on the main (UI) thread.
  2. Step 2: Match with CoroutineScope usage

    Using CoroutineScope(Dispatchers.Main).launch { ... } correctly launches coroutine on main thread.
  3. Final Answer:

    CoroutineScope(Dispatchers.Main).launch { /* code */ } -> Option B
  4. Quick Check:

    Main thread = Dispatchers.Main [OK]
Hint: Main thread uses Dispatchers.Main [OK]
Common Mistakes:
  • Using Dispatchers.IO for UI updates
  • Confusing Default with Main dispatcher
  • Using Unconfined without understanding
3. What will be the output of this Kotlin code snippet?
fun main() = runBlocking {
  launch(Dispatchers.Default) {
    println("Running on thread: ${Thread.currentThread().name}")
  }
}
medium
A. Running on thread: DefaultDispatcher-worker-1
B. Running on thread: Unconfined
C. Running on thread: IO-thread-1
D. Running on thread: main

Solution

  1. Step 1: Understand Dispatchers.Default behavior

    Dispatchers.Default runs coroutines on a shared background thread pool, named like DefaultDispatcher-worker-1.
  2. Step 2: Analyze thread name printed

    The println shows the thread name, which will be a DefaultDispatcher worker thread, not main or IO.
  3. Final Answer:

    Running on thread: DefaultDispatcher-worker-1 -> Option A
  4. Quick Check:

    Dispatchers.Default = DefaultDispatcher-worker thread [OK]
Hint: Default dispatcher uses DefaultDispatcher-worker threads [OK]
Common Mistakes:
  • Assuming main thread runs Default dispatcher
  • Confusing IO dispatcher with Default
  • Expecting Unconfined thread name
4. Identify the error in this Kotlin coroutine code:
CoroutineScope(Dispatchers.Main).launch {
  val result = withContext(Dispatchers.IO) {
    fetchData()
  }
  updateUI(result)
}

fun fetchData(): String {
  Thread.sleep(1000)
  return "Data"
}

fun updateUI(data: String) {
  println(data)
}
medium
A. updateUI() cannot be called inside coroutine.
B. withContext cannot switch dispatchers inside launch.
C. CoroutineScope cannot be created with Dispatchers.Main.
D. Using Thread.sleep() blocks the IO dispatcher thread.

Solution

  1. Step 1: Check blocking calls inside coroutine

    Thread.sleep() blocks the thread, which is bad even on IO dispatcher as it wastes thread resources.
  2. Step 2: Understand coroutine-friendly alternatives

    Instead of Thread.sleep(), use delay() which suspends without blocking the thread.
  3. Final Answer:

    Using Thread.sleep() blocks the IO dispatcher thread. -> Option D
  4. Quick Check:

    Blocking calls like Thread.sleep() cause issues [OK]
Hint: Avoid Thread.sleep() in coroutines; use delay() [OK]
Common Mistakes:
  • Thinking withContext can't switch dispatchers
  • Believing CoroutineScope can't use Dispatchers.Main
  • Assuming updateUI() can't run in coroutine
5. You want to perform a long-running network request without blocking the UI, then update the UI with the result. Which coroutine setup is best practice?
hard
A. Launch coroutine in Dispatchers.Main, then use withContext(Dispatchers.IO) for network call, update UI after.
B. Launch coroutine in Dispatchers.IO, then update UI directly inside it.
C. Launch coroutine in Dispatchers.Default, then use Thread.sleep() for delay, update UI after.
D. Launch coroutine in Dispatchers.Unconfined, then update UI after network call.

Solution

  1. Step 1: Identify correct dispatcher for network call

    Network calls should run on Dispatchers.IO to avoid blocking the main thread.
  2. Step 2: Update UI on main thread

    UI updates must happen on Dispatchers.Main to avoid errors and keep UI responsive.
  3. Step 3: Combine withContext and launch properly

    Launch on Main, switch to IO for network call with withContext, then back to Main for UI update.
  4. Final Answer:

    Launch coroutine in Dispatchers.Main, then use withContext(Dispatchers.IO) for network call, update UI after. -> Option A
  5. Quick Check:

    Network on IO, UI on Main [OK]
Hint: Use withContext(IO) inside Main coroutine for network [OK]
Common Mistakes:
  • Updating UI from IO dispatcher
  • Blocking threads with Thread.sleep()
  • Using Unconfined dispatcher for UI updates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard