blob: 84bb324972d8eb26348a1cb809aab49001f7845d [file] [log] [blame]
Roman Elizarove22f14a2017-06-22 19:04:52 +03001/*
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03002 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarove22f14a2017-06-22 19:04:52 +03003 */
4
5package kotlinx.coroutines.experimental
6
7import kotlin.coroutines.experimental.Continuation
8
9@PublishedApi internal const val MODE_ATOMIC_DEFAULT = 0 // schedule non-cancellable dispatch for suspendCoroutine
10@PublishedApi internal const val MODE_CANCELLABLE = 1 // schedule cancellable dispatch for suspendCancellableCoroutine
11@PublishedApi internal const val MODE_DIRECT = 2 // when the context is right just invoke the delegate continuation direct
12@PublishedApi internal const val MODE_UNDISPATCHED = 3 // when the thread is right, but need to mark it with current coroutine
Roman Elizarov8b38fa22017-09-27 17:44:31 +030013@PublishedApi internal const val MODE_IGNORE = 4 // don't do anything
Roman Elizarove22f14a2017-06-22 19:04:52 +030014
Roman Elizarovac480702017-12-28 01:09:43 +030015internal val Int.isCancellableMode get() = this == MODE_CANCELLABLE
16internal val Int.isDispatchedMode get() = this == MODE_ATOMIC_DEFAULT || this == MODE_CANCELLABLE
17
Roman Elizarove1c0b652017-12-01 14:02:57 +030018internal fun <T> Continuation<T>.resumeMode(value: T, mode: Int) {
Roman Elizarove22f14a2017-06-22 19:04:52 +030019 when (mode) {
20 MODE_ATOMIC_DEFAULT -> resume(value)
21 MODE_CANCELLABLE -> resumeCancellable(value)
22 MODE_DIRECT -> resumeDirect(value)
23 MODE_UNDISPATCHED -> (this as DispatchedContinuation).resumeUndispatched(value)
Roman Elizarov8b38fa22017-09-27 17:44:31 +030024 MODE_IGNORE -> {}
Roman Elizarove22f14a2017-06-22 19:04:52 +030025 else -> error("Invalid mode $mode")
26 }
27}
28
Roman Elizarove1c0b652017-12-01 14:02:57 +030029internal fun <T> Continuation<T>.resumeWithExceptionMode(exception: Throwable, mode: Int) {
Roman Elizarove22f14a2017-06-22 19:04:52 +030030 when (mode) {
31 MODE_ATOMIC_DEFAULT -> resumeWithException(exception)
32 MODE_CANCELLABLE -> resumeCancellableWithException(exception)
33 MODE_DIRECT -> resumeDirectWithException(exception)
34 MODE_UNDISPATCHED -> (this as DispatchedContinuation).resumeUndispatchedWithException(exception)
Roman Elizarov8b38fa22017-09-27 17:44:31 +030035 MODE_IGNORE -> {}
Roman Elizarove22f14a2017-06-22 19:04:52 +030036 else -> error("Invalid mode $mode")
37 }
38}