-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathCoroutineContext.kt
67 lines (52 loc) · 2.61 KB
/
CoroutineContext.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlinx.coroutines.internal.*
import kotlin.coroutines.*
import kotlin.native.concurrent.*
internal actual object DefaultExecutor : CoroutineDispatcher(), Delay {
private val delegate = WorkerDispatcher(name = "DefaultExecutor")
override fun dispatch(context: CoroutineContext, block: Runnable) {
checkState()
delegate.dispatch(context, block)
}
override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) {
checkState()
delegate.scheduleResumeAfterDelay(timeMillis, continuation)
}
override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle {
checkState()
return delegate.invokeOnTimeout(timeMillis, block, context)
}
actual fun enqueue(task: Runnable): Unit {
checkState()
delegate.dispatch(EmptyCoroutineContext, task)
}
private fun checkState() {
if (multithreadingSupported) return
error("DefaultExecutor should never be invoked in K/N with disabled new memory model. The top-most 'runBlocking' event loop has been shutdown")
}
}
internal expect fun createDefaultDispatcher(): CoroutineDispatcher
@SharedImmutable
@PublishedApi
internal val NonMockedDefaultDelay: Delay = if (multithreadingSupported) DefaultExecutor else OldDefaultExecutor
internal actual val DefaultDelay: Delay
get() = Dispatchers.Main as? Delay ?: NonMockedDefaultDelay
public actual fun CoroutineScope.newCoroutineContext(context: CoroutineContext): CoroutineContext {
val combined = coroutineContext + context
return if (combined !== DefaultDelay && combined[ContinuationInterceptor] == null)
combined + (DefaultDelay as CoroutineContext.Element) else combined
}
// No debugging facilities on native
internal actual inline fun <T> withCoroutineContext(context: CoroutineContext, countOrElement: Any?, block: () -> T): T = block()
internal actual inline fun <T> withContinuationContext(continuation: Continuation<*>, countOrElement: Any?, block: () -> T): T = block()
internal actual fun Continuation<*>.toDebugString(): String = toString()
internal actual val CoroutineContext.coroutineName: String? get() = null // not supported on native
internal actual class UndispatchedCoroutine<in T> actual constructor(
context: CoroutineContext,
uCont: Continuation<T>
) : ScopeCoroutine<T>(context, uCont) {
override fun afterResume(state: Any?) = uCont.resumeWith(recoverResult(state, uCont))
}