blob: 5837ae83f3ca18970bcd31387b99ef2f8ac793da [file] [log] [blame]
Roman Elizarovaa461cf2018-04-11 13:20:29 +03001/*
Aurimas Liutikas79e555e2021-05-17 17:41:41 +00002 * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarovaa461cf2018-04-11 13:20:29 +03003 */
4
Roman Elizarov0950dfa2018-07-13 10:33:25 +03005package kotlinx.coroutines
Roman Elizarovaa461cf2018-04-11 13:20:29 +03006
Roman Elizarov0950dfa2018-07-13 10:33:25 +03007import kotlin.coroutines.*
Roman Elizarov8f1f2522019-11-23 18:21:22 +03008import kotlin.jvm.*
Roman Elizarovaa461cf2018-04-11 13:20:29 +03009
10/**
11 * A coroutine dispatcher that is not confined to any specific thread.
Roman Elizarovaa461cf2018-04-11 13:20:29 +030012 */
Vsevolod Tolstopyatov1f7b2d82018-10-09 15:57:51 +030013internal object Unconfined : CoroutineDispatcher() {
Steve Elliottca095be2022-07-25 14:26:10 +000014
15 @ExperimentalCoroutinesApi
16 override fun limitedParallelism(parallelism: Int): CoroutineDispatcher {
17 throw UnsupportedOperationException("limitedParallelism is not supported for Dispatchers.Unconfined")
18 }
19
Vsevolod Tolstopyatovfd54bc42018-10-17 18:37:36 +030020 override fun isDispatchNeeded(context: CoroutineContext): Boolean = false
Roman Elizarov8f1f2522019-11-23 18:21:22 +030021
22 override fun dispatch(context: CoroutineContext, block: Runnable) {
Steve Elliottca095be2022-07-25 14:26:10 +000023 /** It can only be called by the [yield] function. See also code of [yield] function. */
Roman Elizarov8f1f2522019-11-23 18:21:22 +030024 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 }
Roman Elizarov69d1d412019-11-26 11:33:08 +030030 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.")
Roman Elizarov8f1f2522019-11-23 18:21:22 +030033 }
34
Vsevolod Tolstopyatovad542c42020-06-17 04:43:28 -070035 override fun toString(): String = "Dispatchers.Unconfined"
Roman Elizarovaa461cf2018-04-11 13:20:29 +030036}
Roman Elizarov8f1f2522019-11-23 18:21:22 +030037
38/**
39 * Used to detect calls to [Unconfined.dispatch] from [yield] function.
40 */
Steve Elliottca095be2022-07-25 14:26:10 +000041@PublishedApi
Roman Elizarov8f1f2522019-11-23 18:21:22 +030042internal class YieldContext : AbstractCoroutineContextElement(Key) {
43 companion object Key : CoroutineContext.Key<YieldContext>
44
45 @JvmField
46 var dispatcherWasUnconfined = false
Vsevolod Tolstopyatov6d1a6e32020-02-18 15:28:00 +030047}