open fun isDispatchNeeded(context: CoroutineContext): Boolean (source)

Returns true if the execution of the coroutine should be performed with dispatch method. The default behavior for most dispatchers is to return true.

If this method returns false, the coroutine is resumed immediately in the current thread, potentially forming an event-loop to prevent stack overflows. The event loop is an advanced topic and its implications can be found in Dispatchers.Unconfined documentation.

A dispatcher can override this method to provide a performance optimization and avoid paying a cost of an unnecessary dispatch. E.g. MainCoroutineDispatcher.immediate checks whether we are already in the required UI thread in this method and avoids an additional dispatch when it is not required.

While this approach can be more efficient, it is not chosen by default to provide a consistent dispatching behaviour so that users won’t observe unexpected and non-consistent order of events by default.

Coroutine builders like launch and async accept an optional CoroutineStart parameter that allows one to optionally choose the undispatched behavior to start coroutine immediately, but to be resumed only in the provided dispatcher.

This method should generally be exception-safe. An exception thrown from this method may leave the coroutines that use this dispatcher in the inconsistent and hard to debug state.