Kotlin

withContext — Switching Dispatchers

admin by @admin ADMIN
Jun 19, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`withContext(dispatcher)` suspends the calling coroutine, runs the block on the given dispatcher, returns the result. Use `Dispatchers.IO` for blocking I/O, `Default` for CPU work, `Main` for UI updates.
Kotlin
Raw
import kotlinx.coroutines.*
import java.nio.file.*

suspend fun readFileSafely(path: String): String =
    withContext(Dispatchers.IO) {
        // This block runs on the IO thread pool — won't block the caller's
        // dispatcher (e.g. the UI thread on Android).
        Files.readString(Path.of(path))
    }

suspend fun computeHeavyStuff(n: Int): Long =
    withContext(Dispatchers.Default) {
        // CPU-bound work — Default has CPU-count threads
        (1L..n).map { it * it }.sum()
    }

fun main() = runBlocking {
    val contents = readFileSafely("/etc/hostname")
    val checksum = computeHeavyStuff(1_000_000)
    println("file size=${contents.length}, checksum=$checksum")

    // Common pattern: pull the IO into a suspend wrapper so callers don't
    // think about threading.
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.