Coroutines Basics Flashcards
KOTLIN › Concurrency
- What does the suspend keyword do, and how does it work under the hood?
- It marks a function that can pause and resume without blocking the thread. The compiler applies a CPS (continuation-passing style) transformation, adding a hidden Continuation parameter and turning the function body into a state machine that saves/restores state across suspension points.
- Does a suspend function block the thread while it waits?
- No. It suspends the coroutine and frees the underlying thread to do other work; execution resumes later (possibly on a different thread). Blocking a thread keeps it idle and wastes it; suspending does not.
- What is the difference between launch and async?
- launch starts a coroutine for its side effects and returns a Job (no result). async starts a coroutine that computes a value and returns a Deferred<T>; you call await() to suspend until the result is ready. Use async only when you need a result, typically for parallel decomposition.
- What does await() do on a Deferred, and does it block?
- It suspends the calling coroutine until the Deferred completes and then returns its result (or rethrows its exception). It suspends, it does not block the thread.
- What is a CoroutineScope and why does it matter?
- A scope ties coroutines to a lifecycle and holds a CoroutineContext (dispatcher, Job, etc.). It enables structured concurrency: coroutines launched in a scope are its children, the scope waits for them, and cancelling the scope cancels all children. Examples: viewModelScope, lifecycleScope.
- What is the role of a CoroutineDispatcher?
- It decides which thread or thread pool a coroutine runs on. It can confine a coroutine to one thread, dispatch it to a pool, or run it unconfined. It is the dispatcher element of the CoroutineContext.
- When do you use Dispatchers.Main vs IO vs Default?
- Main: UI updates and interacting with the main thread. IO: blocking I/O such as network, disk, and database (large elastic pool). Default: CPU-intensive work like sorting, parsing, or JSON processing (pool sized to CPU cores).
- What does Dispatchers.Unconfined do, and should you use it?
- It starts the coroutine in the caller thread but only until the first suspension point; after resuming it runs on whatever thread the suspending function resumed on. It is an advanced tool not for general application code.
- What is withContext and how does it make a function main-safe?
- withContext(context) suspends, switches the coroutine to the given dispatcher/context, runs the block, returns the result, and switches back. Wrapping blocking work in withContext(Dispatchers.IO) inside a suspend function makes it safe to call from the main thread.