We use withContext to switch the thread or dispatcher in Kotlin coroutines. It helps run code on the right thread, like doing heavy work in the background and updating UI on the main thread.
WithContext for dispatcher switching in Kotlin
suspend fun someFunction() { withContext(Dispatchers.IO) { // code to run on this dispatcher } }
withContext is a suspend function, so it must be called from a coroutine or another suspend function.
You pass a dispatcher like Dispatchers.IO or Dispatchers.Main to tell where the code should run.
withContext(Dispatchers.IO) {
// run blocking IO task here
}withContext(Dispatchers.Main) {
// update UI here
}val result = withContext(Dispatchers.Default) { // do CPU heavy work 42 }
This program starts on the main thread, switches to IO dispatcher to simulate loading data, then switches back to the main thread to print the result.
import kotlinx.coroutines.* fun main() = runBlocking { println("Start on thread: ${Thread.currentThread().name}") val data = withContext(Dispatchers.IO) { println("Working on thread: ${Thread.currentThread().name}") // Simulate slow IO task delay(500) "Data loaded" } println("Back on thread: ${Thread.currentThread().name}") println("Result: $data") println("End on thread: ${Thread.currentThread().name}") }
Always use withContext inside a coroutine or suspend function.
Switching dispatchers helps keep your app responsive and avoids freezing the screen.
Common dispatchers are Dispatchers.Main for UI, Dispatchers.IO for input/output, and Dispatchers.Default for CPU work.
withContext lets you run code on a specific thread or dispatcher inside coroutines.
Use it to keep your app smooth by moving heavy work off the main thread.
Remember to call it only from suspend functions or coroutines.