CoroutineDispatcher is an abstract implementation of ContinuationInterceptor that is used for the implementation of all the provided dispatchers, such as CommonPool, Unconfined, and DefaultDispatcher. Let's look at its code:
public abstract class CoroutineDispatcher :
AbstractCoroutineContextElement(ContinuationInterceptor),
ContinuationInterceptor {
open fun isDispatchNeeded(context: CoroutineContext): Boolean = true
abstract fun dispatch(context: CoroutineContext, block: Runnable)
override fun <T> interceptContinuation(continuation: Continuation<T>):
Continuation<T> = DispatchedContinuation(this, continuation)
public operator fun plus(other: CoroutineDispatcher) = other
override fun toString(): String = "$classSimpleName@$hexAddress"
}
Notice that this class provides an implementation for interceptContinuation() that returns a DispatchedContinuation. It also defines an abstract function, dispatch(), which takes the context and a Runnable. This Runnable is an expected declaration of an interface with a single run() function:
public expect interface Runnable {
public fun run()
}
The actual implementation for the JVM is of course java.lang.Runnable:
public actual typealias Runnable = java.lang.Runnable
Before we move on to look at DispatchedContinuation, it's important that we see some of the implementations of the dispatch function. Bear in mind that this dispatch() function is the one that actually enforces the thread switching, if needed .