What is withContext in Kotlin: Explanation and Example
withContext in Kotlin is a suspend function that switches the coroutine context to a different dispatcher or thread pool temporarily. It helps run code in a specific context like background threads without blocking the main thread.How It Works
Imagine you are cooking in your kitchen (main thread), but some tasks like chopping vegetables (heavy work) are better done by a helper in another room (background thread). withContext lets you send that task to the helper and wait for it to finish before continuing.
Technically, withContext changes the coroutine's context to another dispatcher, such as Dispatchers.IO for input/output tasks or Dispatchers.Default for CPU-heavy work. It suspends the current coroutine, runs the block of code in the new context, and then resumes the coroutine with the result.
This way, your main thread stays free and responsive, while heavy or blocking tasks run safely elsewhere.
Example
This example shows how withContext switches to a background thread to simulate a long-running task, then returns the result to the main thread.
import kotlinx.coroutines.* fun main() = runBlocking { println("Start on thread: ${Thread.currentThread().name}") val result = withContext(Dispatchers.Default) { println("Working in background on thread: ${Thread.currentThread().name}") delay(1000) // Simulate work "Task Complete" } println("Result: $result on thread: ${Thread.currentThread().name}") }
When to Use
Use withContext when you want to run a block of code on a different thread or dispatcher without blocking the current coroutine. This is common for tasks like:
- Reading or writing files
- Making network requests
- Performing CPU-intensive calculations
It helps keep your app responsive by offloading heavy work to appropriate threads and then returning the result safely.
Key Points
withContextis a suspend function that switches coroutine context temporarily.- It helps run code on different threads without blocking the main thread.
- Commonly used with
Dispatchers.IOorDispatchers.Default. - It suspends the current coroutine until the block finishes and returns the result.
Key Takeaways
withContext switches coroutine context to run code on a different thread safely.Dispatchers.IO for I/O and Dispatchers.Default for CPU work.