liveBook · Manning

Dispatchers.IO

As explained in Kotlin in Action, 2E

Dispatchers.IO is the Kotlin coroutines dispatcher backed by an automatically scaling thread pool for blocking input/output operations.

Dispatchers.IO runs coroutines that call blocking input/output APIs on an automatically scaling thread pool. Use it when the operation would otherwise occupy a thread while waiting. section 14.7.1 section 14.9

Switch to the I/O dispatcher

suspend fun loadData(): Data = withContext(Dispatchers.IO) { blockingApiCall() } `withContext` moves this blocking operation to Dispatchers.IO while keeping the surrounding code sequential. Choose Dispatchers.Default for general-purpose work unless blocking APIs or another special requirement calls for a different dispatcher. section 14.7.1 section 14.9

Table 14.2 Dispatchers available out of the box in Kotlin coroutines (view table figure)

Dispatcher

Number of threads

Used for

Dispatchers.Default

Number of CPU cores

General-purpose operations, CPU-bound operations

Dispatchers.Main

One

UI-bound logic (“UI thread”), only when in the context of a UI framework

Dispatchers.IO

Up to 64 threads (auto-scaling) or number of CPU cores (whichever is larger)

Offloading blocking IO tasks

Dispatchers.Unconfined

- (“Whatever thread”)

Advanced cases where immediate scheduling is required (non-general-purpose)

limitedParallelism(n)

Custom (n)

Custom scenarios

Compare Dispatchers.IO with Default, Main, Unconfined, and limitedParallelism by thread count and intended use. section 14.7.1

How Kotlin in Action, 2E covers it

How deep it goes
Defines the dispatcher’s purpose and scaling capacity but stops short of implementation internals.
Examples
Uses a withContext block around a blocking API call and contrasts I/O work with general-purpose dispatcher selection.
What it assumes
Assumes familiarity with coroutines and blocking operations while relating dispatcher choice to coroutine context.
What you can do after
Apply it via withContext to execute blocking I/O tasks on an appropriate coroutine dispatcher.
How it connects
Connects Dispatchers.IO with coroutines, withContext, Dispatchers.Default, Dispatchers.Main, and coroutine context.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.