import kotlinx.coroutines.*
suspend fun fetchUser(id: Int): String {
delay(100) // non-blocking pause (vs Thread.sleep)
return "User $id"
}
fun main() = runBlocking { // bridge from non-coroutine main
println("starting at ${System.currentTimeMillis()}")
val user = fetchUser(42)
println(user)
println("done at ${System.currentTimeMillis()}")
}
// Key points:
// • `suspend` is a marker on the function signature — the compiler rewrites
// the body into a state machine that can pause at every `suspend` call.
// • A suspend function called from another suspend function is just a normal
// sequential call; threads aren't tied up while waiting.
// • Use `Dispatchers.IO` / `Dispatchers.Default` (via withContext) to choose
// what thread pool runs the work — see other snippets.
Create a free account and build your private vault. Share publicly whenever you want.