Part 14 / Topic 1 of 7
suspend functions
A suspend function is one that can pause -- without blocking the underlying OS thread
-- and resume later. It can only be called from another suspend function, or from inside a
coroutine (the builders in Section 2). This is the single biggest difference from a normal
blocking call: Thread.sleep ties up a whole thread while "waiting"; delay (a suspend
function from the coroutines library) frees the thread for other work and comes back later.
suspend fun fetchEta(partner: String): String {
delay(300) // suspends: frees the thread to do other work while "waiting"
return "$partner: ETA 12 min"
}
fun blockingFetchEta(partner: String): String {
Thread.sleep(300)
return "$partner: ETA 12 min (blocking)"
}
Real-world example: Swadesh Mart's quick-commerce arm checks delivery-partner ETAs (Swiggy, Zomato, Dunzo-style partners) before confirming an order slot.
fun main() = runBlocking {
val suspendTime = measureTimeMillis {
println(fetchEta("Swiggy"))
println(fetchEta("Zomato"))
}
println("Two suspend calls, one after another: ${suspendTime}ms (varies, ~600ms)")
val blockingTime = measureTimeMillis {
println(blockingFetchEta("Swiggy"))
println(blockingFetchEta("Zomato"))
}
println("Two blocking calls, one after another: ${blockingTime}ms (varies, ~600ms)")
}
Swiggy: ETA 12 min
Zomato: ETA 12 min
Two suspend calls, one after another: 607ms (varies, ~600ms)
Swiggy: ETA 12 min (blocking)
Zomato: ETA 12 min (blocking)
Two blocking calls, one after another: 609ms (varies, ~600ms)
Called one after another like this, delay and Thread.sleep take the same wall-clock time --
the difference only shows up once something else could be running at the same time on that
thread, which Section 2 (and especially Section 5) makes visible.
Full program: examples/01_suspend_functions.kt.
Done here? The practice set for Part 14 — including the solutions — is on the part page.