• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016-2020 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 import kotlin.jvm.*
9 
10 /**
11  * A coroutine dispatcher that is not confined to any specific thread.
12  */
13 internal object Unconfined : CoroutineDispatcher() {
isDispatchNeedednull14     override fun isDispatchNeeded(context: CoroutineContext): Boolean = false
15 
16     override fun dispatch(context: CoroutineContext, block: Runnable) {
17         // It can only be called by the "yield" function. See also code of "yield" function.
18         val yieldContext = context[YieldContext]
19         if (yieldContext != null) {
20             // report to "yield" that it is an unconfined dispatcher and don't call "block.run()"
21             yieldContext.dispatcherWasUnconfined = true
22             return
23         }
24         throw UnsupportedOperationException("Dispatchers.Unconfined.dispatch function can only be used by the yield function. " +
25             "If you wrap Unconfined dispatcher in your code, make sure you properly delegate " +
26             "isDispatchNeeded and dispatch calls.")
27     }
28 
toStringnull29     override fun toString(): String = "Dispatchers.Unconfined"
30 }
31 
32 /**
33  * Used to detect calls to [Unconfined.dispatch] from [yield] function.
34  */
35 internal class YieldContext : AbstractCoroutineContextElement(Key) {
36     companion object Key : CoroutineContext.Key<YieldContext>
37 
38     @JvmField
39     var dispatcherWasUnconfined = false
40 }
41