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 import kotlin.jvm.* 9 10 /** 11 * A coroutine dispatcher that is not confined to any specific thread. 12 */ 13 internal object Unconfined : CoroutineDispatcher() { 14 15 @ExperimentalCoroutinesApi limitedParallelismnull16 override fun limitedParallelism(parallelism: Int): CoroutineDispatcher { 17 throw UnsupportedOperationException("limitedParallelism is not supported for Dispatchers.Unconfined") 18 } 19 isDispatchNeedednull20 override fun isDispatchNeeded(context: CoroutineContext): Boolean = false 21 22 override fun dispatch(context: CoroutineContext, block: Runnable) { 23 /** It can only be called by the [yield] function. See also code of [yield] function. */ 24 val yieldContext = context[YieldContext] 25 if (yieldContext != null) { 26 // report to "yield" that it is an unconfined dispatcher and don't call "block.run()" 27 yieldContext.dispatcherWasUnconfined = true 28 return 29 } 30 throw UnsupportedOperationException("Dispatchers.Unconfined.dispatch function can only be used by the yield function. " + 31 "If you wrap Unconfined dispatcher in your code, make sure you properly delegate " + 32 "isDispatchNeeded and dispatch calls.") 33 } 34 toStringnull35 override fun toString(): String = "Dispatchers.Unconfined" 36 } 37 38 /** 39 * Used to detect calls to [Unconfined.dispatch] from [yield] function. 40 */ 41 @PublishedApi 42 internal class YieldContext : AbstractCoroutineContextElement(Key) { 43 companion object Key : CoroutineContext.Key<YieldContext> 44 45 @JvmField 46 var dispatcherWasUnconfined = false 47 } 48