• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016-2021 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 import kotlin.coroutines.*
8 
9 public actual object Dispatchers {
10     public actual val Default: CoroutineDispatcher = createDefaultDispatcher()
11     public actual val Main: MainCoroutineDispatcher
12         get() = injectedMainDispatcher ?: mainDispatcher
13     public actual val Unconfined: CoroutineDispatcher = kotlinx.coroutines.Unconfined
14 
15     private val mainDispatcher = JsMainDispatcher(Default, false)
16     private var injectedMainDispatcher: MainCoroutineDispatcher? = null
17 
18     @PublishedApi
injectMainnull19     internal fun injectMain(dispatcher: MainCoroutineDispatcher) {
20         injectedMainDispatcher = dispatcher
21     }
22 }
23 
24 private class JsMainDispatcher(
25     val delegate: CoroutineDispatcher,
26     private val invokeImmediately: Boolean
27 ) : MainCoroutineDispatcher() {
28     override val immediate: MainCoroutineDispatcher =
29         if (invokeImmediately) this else JsMainDispatcher(delegate, true)
isDispatchNeedednull30     override fun isDispatchNeeded(context: CoroutineContext): Boolean = !invokeImmediately
31     override fun dispatch(context: CoroutineContext, block: Runnable) = delegate.dispatch(context, block)
32     override fun dispatchYield(context: CoroutineContext, block: Runnable) = delegate.dispatchYield(context, block)
33     override fun toString(): String = toStringInternalImpl() ?: delegate.toString()
34 }
35