1 /* 2 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 package kotlinx.coroutines 6 7 /** 8 * Base class for special [CoroutineDispatcher] which is confined to application "Main" or "UI" thread 9 * and used for any UI-based activities. Instance of `MainDispatcher` can be obtained by [Dispatchers.Main]. 10 * 11 * Platform may or may not provide instance of `MainDispatcher`, see documentation to [Dispatchers.Main] 12 */ 13 public abstract class MainCoroutineDispatcher : CoroutineDispatcher() { 14 15 /** 16 * Returns dispatcher that executes coroutines immediately when it is already in the right context 17 * (e.g. current looper is the same as this handler's looper) without an additional [re-dispatch][CoroutineDispatcher.dispatch]. 18 * 19 * Immediate dispatcher is safe from stack overflows and in case of nested invocations forms event-loop similar to [Dispatchers.Unconfined]. 20 * The event loop is an advanced topic and its implications can be found in [Dispatchers.Unconfined] documentation. 21 * 22 * Example of usage: 23 * ``` 24 * suspend fun updateUiElement(val text: String) { 25 * /* 26 * * If it is known that updateUiElement can be invoked both from the Main thread and from other threads, 27 * * `immediate` dispatcher is used as a performance optimization to avoid unnecessary dispatch. 28 * * 29 * * In that case, when `updateUiElement` is invoked from the Main thread, `uiElement.text` will be 30 * * invoked immediately without any dispatching, otherwise, the `Dispatchers.Main` dispatch cycle will be triggered. 31 * */ 32 * withContext(Dispatchers.Main.immediate) { 33 * uiElement.text = text 34 * } 35 * // Do context-independent logic such as logging 36 * } 37 * ``` 38 * 39 * Method may throw [UnsupportedOperationException] if immediate dispatching is not supported by current dispatcher, 40 * please refer to specific dispatcher documentation. 41 * 42 * [Dispatchers.Main] supports immediate execution for Android, JavaFx and Swing platforms. 43 */ 44 public abstract val immediate: MainCoroutineDispatcher 45 } 46