CoroutineDispatcher

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()
}
Expected declarations were added in Kotlin 1.2 in order to support multi-platform projects. Using the keyword expect you can define an API to be implemented on each platform—it supports classes, interfaces, functions, and more. So as we will see here, each platform can have its own implementation as long as it adjusts to the signature that is expected.

The actual implementation for the JVM is of course java.lang.Runnable:

public actual typealias Runnable = java.lang.Runnable
Notice that the implementation of an expected declaration is marked with the keyword actual. In this case, Kotlin's Runnable interface is mapped to Java's for execution in the JVM.

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 .

The isDispatchNeeded() function will be called before dispatch(). If it returns false then the framework will not call dispatch(); instead it will allow the resuming of the Continuation to happen in whichever thread the code is running—which, by default, will match the thread of the previous continuation in the chain.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.60.158