🚀 Enrollments Open for 1:1 Mentorship Scheduled as per your availability 💚Book 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.

1:1 Mentorship

Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.

Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance

Limited slots available each month

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow 💚