Questions
KotlinIntermediate4 min
How does Coroutine switch context?
Answer
Coroutines switch context using Dispatchers and the Continuation passing style (CPS).
- Dispatchers: Determine which thread (or pool) the coroutine runs on (e.g., `Dispatchers.IO`, `Dispatchers.Main`).
- withContext: When you call `withContext(Dispatchers.IO)`, the coroutine suspends on the current thread.
- 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.
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
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚