Blocking occupies the calling thread while it waits. Suspension lets a coroutine pause and later resume without keeping that thread occupied during the wait. The main thread can then process other work; it is not a thread-pool worker that must be returned to a pool.
A legacy blocking file reader needs an appropriate dispatcher even when exposed through a suspending API:
class NotesRepository(
private val ioDispatcher: CoroutineDispatcher
) {
suspend fun readNotes(file: File): String =
withContext(ioDispatcher) {
file.readText()
}
}
Supply an I/O dispatcher in production and control it in tests. The file operation still blocks its worker thread; the caller can suspend while waiting for that work to complete.
Adding suspend to a CPU-heavy parser does not make the parser run in the background. A function may execute without suspending at all. Move substantial CPU work to an appropriate dispatcher, and make long loops cooperate with cancellation.
Should every suspend call be wrapped in withContext(IO)? No. A well-designed suspending API can already be safe to call from Main. Put thread-management responsibility at the layer that performs the blocking work instead of scattering redundant switches through the UI.
Android Developers: Make suspend functions safe to call from Main
Mark this when you can explain the answer in your own words.
Help fellow developers prepare for interviews
Sharing helps the Android community grow ๐