What is the difference between suspending and blocking in Kotlin Coroutines?
Tier: EssentialDifficulty: Easy
Blocking ties up a thread until an operation finishes, the thread can't do anything else in the meantime. Suspending pauses a coroutine and gives the thread back, so that thread can go run other work, then the coroutine resumes later, possibly on a different thread.
fun blockingWait() {
Thread.sleep(1000) // thread is stuck here, nothing else runs on it
}
suspend fun suspendingWait() {
delay(1000) // coroutine pauses, thread is free to do other work
}
Thread.sleep() blocks. delay() suspends. Both wait a second, but Thread.sleep() freezes whatever thread called it, while delay() releases the thread and only reserves it again when the coroutine actually needs to resume.
On Android this is the whole reason coroutines are worth using. Blocking the main thread for too long freezes the UI and can trigger an ANR. Suspending on the main thread with something like delay() or a suspending network call doesn't block it at all, the UI stays responsive because the thread was never held hostage in the first place.