androidengineers.Book a session
โ† All interview questions
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.

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising