🚀 Enrollments Open for Jetpack Compose Cohort 2 — 7 Days of Live Learning to Build Modern Android UIs 💚Join Now
KotlinIntermediate4 min
How does Coroutine switch context?

Answer

Coroutines switch context using Dispatchers and the Continuation passing style (CPS).

  1. Dispatchers: Determine which thread (or pool) the coroutine runs on (e.g., `Dispatchers.IO`, `Dispatchers.Main`).
  2. withContext: When you call `withContext(Dispatchers.IO)`, the coroutine suspends on the current thread.
  3. Under the hood:
    • The state machine saves the current progress.
    • The task is submitted to the target Dispatcher's thread pool.
    • When the task finishes, it signals the original dispatcher to resume the coroutine.

This is much cheaper than an OS thread context switch because it's handled by the language runtime and doesn't necessarily involve the OS kernel scheduler.

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

Accelerate Your Growth

Don't just learn concepts in isolation. Build production-ready Android apps with expert guidance.

Live Interactive Sessions
Code Reviews & Feedback
Real-world Projects
Career Guidance

Limited seats available for next cohort