DispatcherProvider

Abstraction over the four standard dispatchers, meant to be injected into classes instead of hardcoding Dispatchers.* so tests can swap in a test dispatcher with virtual time.

Example:

class UserRepository(private val dispatchers: DispatcherProvider = DefaultDispatcherProvider) {
suspend fun load() = withContext(dispatchers.io) { api.fetch() }
}

// In a test:
val repo = UserRepository(DispatcherProvider.of(StandardTestDispatcher(testScheduler)))

Rules: DISPATCH_005 (inject dispatchers for testability), KMP_001 (no Dispatchers.IO in commonMain; see ioCompat), TEST_005 (no hardcoded dispatcher in a class). See docs/BEST_PRACTICES_COROUTINES.md sections 3.5, 11.1 and 6.5.

Requires opting in to ExperimentalStructuredCoroutines. Any provider can be wrapped by traced (event tracing) or instrumented (basic diagnostics).

See also

Inheritors

Types

Link copied to clipboard
object Companion

Properties

Link copied to clipboard

Dispatcher for CPU-bound work.

Link copied to clipboard
abstract val io: CoroutineDispatcher

Dispatcher for blocking IO. The default implementation resolves it through ioCompat.

Link copied to clipboard

UI dispatcher. May be unavailable on platforms without a main dispatcher (for example a plain JVM process without a UI toolkit); in that case accessing it fails the way Dispatchers.Main does.

Link copied to clipboard

Unconfined dispatcher. Runs in the caller thread until the first suspension; avoid for work that needs thread affinity.

Functions

Link copied to clipboard

Wraps this provider's main, io and default dispatchers in InstrumentedDispatchers with those labels; unconfined is returned as is (see InstrumentedDispatcherProvider). Wrapping is lazy: nothing (including Dispatchers.Main) is read until the corresponding property is accessed.

Link copied to clipboard

Wraps this provider's main, io and default dispatchers in TracingDispatchers labeled "main", "io" and "default" that report to sink. unconfined is returned as is.