🐦 Kotlin
Intermediate
What is withContext in Kotlin coroutines?
Answer
withContext(dispatcher) is a suspend function that switches the coroutine to a different dispatcher for the duration of the block, then switches back. It is the idiomatic way to perform off-main-thread work: val result = withContext(Dispatchers.IO) { api.fetchData() }. Unlike async { }.await(), withContext does not create a new coroutine — it reuses the current coroutine's Job, making it more efficient for a single sequential task. Use it whenever you need to change the execution context for a specific operation, like moving I/O work off the main thread and back.