immediate

abstract override val immediate: HandlerDispatcher(source)

Returns dispatcher that executes coroutines immediately when it is already in the right context (current looper is the same as this handler's looper) without an additional re-dispatch. This dispatcher does not use Handler.post when current looper is the same as looper of the handler.

Immediate dispatcher is safe from stack overflows and in case of nested invocations forms event-loop similar to Dispatchers.Unconfined. The event loop is an advanced topic and its implications can be found in Dispatchers.Unconfined documentation.

Example of usage:

suspend fun updateUiElement(val text: String) {
/*
* If it is known that updateUiElement can be invoked both from the Main thread and from other threads,
* `immediate` dispatcher is used as a performance optimization to avoid unnecessary dispatch.
*
* In that case, when `updateUiElement` is invoked from the Main thread, `uiElement.text` will be
* invoked immediately without any dispatching, otherwise, the `Dispatchers.Main` dispatch cycle via
* `Handler.post` will be triggered.
*/
withContext(Dispatchers.Main.immediate) {
uiElement.text = text
}
// Do context-independent logic such as logging
}