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.
}
Create a free account and build your private vault. Share publicly whenever you want.