blob: 0744daaa7c3396a03666ac20b3f98d5e35080b9c [file] [log] [blame]
Roman Elizarovf16fd272017-02-07 11:26:00 +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 Elizarovf16fd272017-02-07 11:26:00 +03003 */
4
Roman Elizarov3754f952017-01-18 20:47:54 +03005package kotlinx.coroutines.experimental
6
Roman Elizarovaa461cf2018-04-11 13:20:29 +03007import kotlinx.coroutines.experimental.internal.*
8import kotlinx.coroutines.experimental.internalAnnotations.*
9import kotlin.coroutines.experimental.*
10import kotlin.coroutines.experimental.intrinsics.*
Roman Elizarov3754f952017-01-18 20:47:54 +030011
12// --------------- cancellable continuations ---------------
13
14/**
Vsevolod Tolstopyatovf6430f42018-04-17 17:56:32 +030015 * Cancellable continuation. It is _completed_ when it is resumed or cancelled.
Roman Elizarovd82b3a92017-06-23 21:52:08 +030016 * When [cancel] function is explicitly invoked, this continuation immediately resumes with [CancellationException] or
Roman Elizarovb7c46de2017-02-08 12:35:24 +030017 * with the specified cancel cause.
18 *
Roman Elizarovd82b3a92017-06-23 21:52:08 +030019 * Cancellable continuation has three states (as subset of [Job] states):
Roman Elizarov32d95322017-02-09 15:57:31 +030020 *
21 * | **State** | [isActive] | [isCompleted] | [isCancelled] |
Roman Elizarov7886ef62017-02-13 14:00:18 +030022 * | ----------------------------------- | ---------- | ------------- | ------------- |
Roman Elizarov32d95322017-02-09 15:57:31 +030023 * | _Active_ (initial state) | `true` | `false` | `false` |
24 * | _Resumed_ (final _completed_ state) | `false` | `true` | `false` |
25 * | _Canceled_ (final _completed_ state)| `false` | `true` | `true` |
Roman Elizarovb7c46de2017-02-08 12:35:24 +030026 *
27 * Invocation of [cancel] transitions this continuation from _active_ to _cancelled_ state, while
28 * invocation of [resume] or [resumeWithException] transitions it from _active_ to _resumed_ state.
29 *
Roman Elizarov29affbb2017-07-21 13:47:41 +030030 * A [cancelled][isCancelled] continuation implies that it is [completed][isCompleted].
Roman Elizarovd82b3a92017-06-23 21:52:08 +030031 *
Roman Elizarovb7c46de2017-02-08 12:35:24 +030032 * Invocation of [resume] or [resumeWithException] in _resumed_ state produces [IllegalStateException]
33 * but is ignored in _cancelled_ state.
Roman Elizarov29affbb2017-07-21 13:47:41 +030034 *
35 * ```
36 * +-----------+ resume +---------+
37 * | Active | ----------> | Resumed |
38 * +-----------+ +---------+
39 * |
40 * | cancel
41 * V
42 * +-----------+
43 * | Cancelled |
44 * +-----------+
45 *
46 * ```
Roman Elizarov3754f952017-01-18 20:47:54 +030047 */
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +030048public interface CancellableContinuation<in T> : Continuation<T> {
Roman Elizarove1c0b652017-12-01 14:02:57 +030049 /**
50 * Returns `true` when this continuation is active -- it has not completed or cancelled yet.
51 */
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +030052 public val isActive: Boolean
Roman Elizarove1c0b652017-12-01 14:02:57 +030053
54 /**
55 * Returns `true` when this continuation has completed for any reason. A continuation
56 * that was cancelled is also considered complete.
57 */
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +030058 public val isCompleted: Boolean
Roman Elizarove1c0b652017-12-01 14:02:57 +030059
Roman Elizarov834af462017-01-23 20:50:29 +030060 /**
Roman Elizarov32d95322017-02-09 15:57:31 +030061 * Returns `true` if this continuation was [cancelled][cancel].
62 *
63 * It implies that [isActive] is `false` and [isCompleted] is `true`.
Roman Elizarov834af462017-01-23 20:50:29 +030064 */
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +030065 public val isCancelled: Boolean
Roman Elizarov187eace2017-01-31 09:39:58 +030066
67 /**
Roman Elizarov7b2d8b02017-02-02 20:09:14 +030068 * Tries to resume this continuation with a given value and returns non-null object token if it was successful,
69 * or `null` otherwise (it was already resumed or cancelled). When non-null object was returned,
70 * [completeResume] must be invoked with it.
Roman Elizarov1216e912017-02-22 09:57:06 +030071 *
72 * When [idempotent] is not `null`, this function performs _idempotent_ operation, so that
73 * further invocations with the same non-null reference produce the same result.
74 *
75 * @suppress **This is unstable API and it is subject to change.**
Roman Elizarov187eace2017-01-31 09:39:58 +030076 */
Roman Elizarovaa461cf2018-04-11 13:20:29 +030077 public fun tryResume(value: T, idempotent: Any? = null): Any?
Roman Elizarov7b2d8b02017-02-02 20:09:14 +030078
79 /**
Roman Elizarovf6fed2a2017-02-03 19:12:09 +030080 * Tries to resume this continuation with a given exception and returns non-null object token if it was successful,
81 * or `null` otherwise (it was already resumed or cancelled). When non-null object was returned,
82 * [completeResume] must be invoked with it.
Roman Elizarov1216e912017-02-22 09:57:06 +030083 *
84 * @suppress **This is unstable API and it is subject to change.**
Roman Elizarovf6fed2a2017-02-03 19:12:09 +030085 */
Roman Elizarova198bad2017-02-10 13:30:38 +030086 public fun tryResumeWithException(exception: Throwable): Any?
Roman Elizarovf6fed2a2017-02-03 19:12:09 +030087
88 /**
89 * Completes the execution of [tryResume] or [tryResumeWithException] on its non-null result.
Roman Elizarov1216e912017-02-22 09:57:06 +030090 *
91 * @suppress **This is unstable API and it is subject to change.**
Roman Elizarov7b2d8b02017-02-02 20:09:14 +030092 */
Roman Elizarovaa461cf2018-04-11 13:20:29 +030093 public fun completeResume(token: Any)
Roman Elizarov187eace2017-01-31 09:39:58 +030094
95 /**
96 * Makes this continuation cancellable. Use it with `holdCancellability` optional parameter to
97 * [suspendCancellableCoroutine] function. It throws [IllegalStateException] if invoked more than once.
98 */
Roman Elizarovaa461cf2018-04-11 13:20:29 +030099 public fun initCancellability()
Roman Elizarove1c0b652017-12-01 14:02:57 +0300100
101 /**
102 * Cancels this continuation with an optional cancellation [cause]. The result is `true` if this continuation was
103 * cancelled as a result of this invocation and `false` otherwise.
104 */
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300105 public fun cancel(cause: Throwable? = null): Boolean
Roman Elizarove1c0b652017-12-01 14:02:57 +0300106
107 /**
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300108 * Registers handler that is **synchronously** invoked once on cancellation (both regular and exceptional) of this continuation.
109 * When the continuation is already cancelled, then the handler is immediately invoked
110 * with cancellation exception. Otherwise, the handler will be invoked once on cancellation if this
111 * continuation is cancelled.
Roman Elizarove1c0b652017-12-01 14:02:57 +0300112 *
113 * Installed [handler] should not throw any exceptions. If it does, they will get caught,
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300114 * wrapped into [CompletionHandlerException], and rethrown, potentially causing the crash of unrelated code.
115 *
116 * At most one [handler] can be installed on one continuation
Vsevolod Tolstopyatovbb19a262018-05-25 19:14:59 +0300117 *
118 * @param invokeImmediately not used
119 * @param onCancelling not used
120 * @return not used
Roman Elizarove1c0b652017-12-01 14:02:57 +0300121 */
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300122 @Deprecated(
123 message = "Disposable handlers on regular completion are no longer supported",
124 replaceWith = ReplaceWith("invokeOnCancellation(handler)"),
Vsevolod Tolstopyatov2cd27fb2018-06-07 13:22:17 +0300125 level = DeprecationLevel.WARNING
Vsevolod Tolstopyatovbb19a262018-05-25 19:14:59 +0300126 )
127 public fun invokeOnCompletion(
128 onCancelling: Boolean = false,
129 invokeImmediately: Boolean = true,
130 handler: CompletionHandler): DisposableHandle
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300131
132 /**
133 * Registers handler that is **synchronously** invoked once on cancellation (both regular and exceptional) of this continuation.
134 * When the continuation is already cancelled, then the handler is immediately invoked
135 * with cancellation exception. Otherwise, the handler will be invoked once on cancellation if this
136 * continuation is cancelled.
137 *
138 * Installed [handler] should not throw any exceptions. If it does, they will get caught,
139 * wrapped into [CompletionHandlerException], and rethrown, potentially causing the crash of unrelated code.
140 *
Roman Elizarov58c5fdc2018-06-08 14:01:12 +0300141 * At most one [handler] can be installed on one continuation.
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300142 */
143 public fun invokeOnCancellation(handler: CompletionHandler)
Roman Elizarova198bad2017-02-10 13:30:38 +0300144
145 /**
146 * Resumes this continuation with a given [value] in the invoker thread without going though
147 * [dispatch][CoroutineDispatcher.dispatch] function of the [CoroutineDispatcher] in the [context].
148 * This function is designed to be used only by the [CoroutineDispatcher] implementations themselves.
149 * **It should not be used in general code**.
Roman Elizarova198bad2017-02-10 13:30:38 +0300150 */
Roman Elizarovaa461cf2018-04-11 13:20:29 +0300151 public fun CoroutineDispatcher.resumeUndispatched(value: T)
Roman Elizarova198bad2017-02-10 13:30:38 +0300152
153 /**
154 * Resumes this continuation with a given [exception] in the invoker thread without going though
155 * [dispatch][CoroutineDispatcher.dispatch] function of the [CoroutineDispatcher] in the [context].
156 * This function is designed to be used only by the [CoroutineDispatcher] implementations themselves.
157 * **It should not be used in general code**.
Roman Elizarova198bad2017-02-10 13:30:38 +0300158 */
Roman Elizarovaa461cf2018-04-11 13:20:29 +0300159 public fun CoroutineDispatcher.resumeUndispatchedWithException(exception: Throwable)
Roman Elizarov834af462017-01-23 20:50:29 +0300160}
Roman Elizarov3754f952017-01-18 20:47:54 +0300161
162/**
Roman Elizarova74eb5f2017-05-11 20:15:18 +0300163 * Suspends coroutine similar to [suspendCoroutine], but provide an implementation of [CancellableContinuation] to
Roman Elizarovd82b3a92017-06-23 21:52:08 +0300164 * the [block]. This function throws [CancellationException] if the coroutine is cancelled or completed while suspended.
Roman Elizarov187eace2017-01-31 09:39:58 +0300165 *
166 * If [holdCancellability] optional parameter is `true`, then the coroutine is suspended, but it is not
167 * cancellable until [CancellableContinuation.initCancellability] is invoked.
Roman Elizarova74eb5f2017-05-11 20:15:18 +0300168 *
169 * See [suspendAtomicCancellableCoroutine] for suspending functions that need *atomic cancellation*.
Roman Elizarov3754f952017-01-18 20:47:54 +0300170 */
Roman Elizarovaa461cf2018-04-11 13:20:29 +0300171public suspend inline fun <T> suspendCancellableCoroutine(
Roman Elizarov187eace2017-01-31 09:39:58 +0300172 holdCancellability: Boolean = false,
173 crossinline block: (CancellableContinuation<T>) -> Unit
174): T =
Roman Elizarov58a7add2017-01-20 12:19:52 +0300175 suspendCoroutineOrReturn { cont ->
Roman Elizarov2b12d582017-06-22 20:12:19 +0300176 val cancellable = CancellableContinuationImpl(cont, resumeMode = MODE_CANCELLABLE)
Roman Elizarovee7c0eb2017-02-16 15:29:28 +0300177 if (!holdCancellability) cancellable.initCancellability()
178 block(cancellable)
179 cancellable.getResult()
Roman Elizarovaa461cf2018-04-11 13:20:29 +0300180 }
Roman Elizarov3754f952017-01-18 20:47:54 +0300181
Roman Elizarova74eb5f2017-05-11 20:15:18 +0300182/**
183 * Suspends coroutine similar to [suspendCancellableCoroutine], but with *atomic cancellation*.
184 *
185 * When suspended function throws [CancellationException] it means that the continuation was not resumed.
186 * As a side-effect of atomic cancellation, a thread-bound coroutine (to some UI thread, for example) may
187 * continue to execute even after it was cancelled from the same thread in the case when the continuation
188 * was already resumed and was posted for execution to the thread's queue.
189 */
Roman Elizarovaa461cf2018-04-11 13:20:29 +0300190public suspend inline fun <T> suspendAtomicCancellableCoroutine(
Roman Elizarova74eb5f2017-05-11 20:15:18 +0300191 holdCancellability: Boolean = false,
192 crossinline block: (CancellableContinuation<T>) -> Unit
193): T =
194 suspendCoroutineOrReturn { cont ->
Roman Elizarov2b12d582017-06-22 20:12:19 +0300195 val cancellable = CancellableContinuationImpl(cont, resumeMode = MODE_ATOMIC_DEFAULT)
Roman Elizarova74eb5f2017-05-11 20:15:18 +0300196 if (!holdCancellability) cancellable.initCancellability()
197 block(cancellable)
198 cancellable.getResult()
199 }
Roman Elizarov0a788392017-02-15 17:52:12 +0300200
201/**
202 * Removes a given node on cancellation.
203 * @suppress **This is unstable API and it is subject to change.**
204 */
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300205@Deprecated(
206 message = "Disposable handlers on cancellation are no longer supported",
207 replaceWith = ReplaceWith("removeOnCancellation(handler)"),
Vsevolod Tolstopyatov2cd27fb2018-06-07 13:22:17 +0300208 level = DeprecationLevel.WARNING)
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300209public fun CancellableContinuation<*>.removeOnCancel(node: LockFreeLinkedListNode): DisposableHandle {
Vsevolod Tolstopyatovf6430f42018-04-17 17:56:32 +0300210 removeOnCancellation(node)
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300211 return NonDisposableHandle
212}
213
214/**
215 * Removes a given node on cancellation.
216 * @suppress **This is unstable API and it is subject to change.**
217 */
Roman Elizarovdbd9e1c2018-04-28 15:14:18 +0300218public fun CancellableContinuation<*>.removeOnCancellation(node: LockFreeLinkedListNode) =
219 invokeOnCancellation(handler = RemoveOnCancel(node).asHandler)
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300220
Vsevolod Tolstopyatov80a29472018-04-17 16:02:02 +0300221/**
222 * Disposes a specified [handle] when this continuation is cancelled.
223 *
224 * This is a shortcut for the following code with slightly more efficient implementation (one fewer object created).
225 * ```
226 * invokeOnCancellation { handle.dispose() }
227 * ```
228 */
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300229@Deprecated(
230 message = "Disposable handlers on regular completion are no longer supported",
231 replaceWith = ReplaceWith("disposeOnCancellation(handler)"),
Vsevolod Tolstopyatov2cd27fb2018-06-07 13:22:17 +0300232 level = DeprecationLevel.WARNING)
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300233public fun CancellableContinuation<*>.disposeOnCompletion(handle: DisposableHandle): DisposableHandle {
Vsevolod Tolstopyatovf6430f42018-04-17 17:56:32 +0300234 disposeOnCancellation(handle)
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300235 return NonDisposableHandle
236}
237
Vsevolod Tolstopyatov80a29472018-04-17 16:02:02 +0300238/**
239 * Disposes a specified [handle] when this continuation is cancelled.
240 *
241 * This is a shortcut for the following code with slightly more efficient implementation (one fewer object created).
242 * ```
243 * invokeOnCancellation { handle.dispose() }
244 * ```
245 */
Roman Elizarovdbd9e1c2018-04-28 15:14:18 +0300246public fun CancellableContinuation<*>.disposeOnCancellation(handle: DisposableHandle) =
247 invokeOnCancellation(handler = DisposeOnCancel(handle).asHandler)
Roman Elizarov0a788392017-02-15 17:52:12 +0300248
Roman Elizarov3754f952017-01-18 20:47:54 +0300249// --------------- implementation details ---------------
250
Roman Elizarovdbd9e1c2018-04-28 15:14:18 +0300251private class RemoveOnCancel(private val node: LockFreeLinkedListNode) : CancelHandler() {
252 override fun invoke(cause: Throwable?) { node.remove() }
Roman Elizarov0a788392017-02-15 17:52:12 +0300253 override fun toString() = "RemoveOnCancel[$node]"
254}
255
Roman Elizarovdbd9e1c2018-04-28 15:14:18 +0300256private class DisposeOnCancel(private val handle: DisposableHandle) : CancelHandler() {
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300257 override fun invoke(cause: Throwable?) = handle.dispose()
Roman Elizarovdbd9e1c2018-04-28 15:14:18 +0300258 override fun toString(): String = "DisposeOnCancel[$handle]"
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300259}
260
Roman Elizarov3754f952017-01-18 20:47:54 +0300261@PublishedApi
Roman Elizarove22f14a2017-06-22 19:04:52 +0300262internal class CancellableContinuationImpl<in T>(
Roman Elizarovbcdd8e12017-10-20 16:42:06 +0800263 delegate: Continuation<T>,
Roman Elizarov2b12d582017-06-22 20:12:19 +0300264 resumeMode: Int
Roman Elizarovac480702017-12-28 01:09:43 +0300265) : AbstractContinuation<T>(delegate, resumeMode), CancellableContinuation<T>, Runnable {
Roman Elizarov2b12d582017-06-22 20:12:19 +0300266
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300267 public override val context: CoroutineContext = delegate.context
Roman Elizarov3754f952017-01-18 20:47:54 +0300268
Roman Elizarov187eace2017-01-31 09:39:58 +0300269 override fun initCancellability() {
Roman Elizarov6640b2b2018-01-17 19:08:55 +0300270 initParentJobInternal(delegate.context[Job])
Roman Elizarov187eace2017-01-31 09:39:58 +0300271 }
Roman Elizarov58a7add2017-01-20 12:19:52 +0300272
Vsevolod Tolstopyatovbb19a262018-05-25 19:14:59 +0300273 override fun invokeOnCompletion(onCancelling: Boolean,
274 invokeImmediately: Boolean, handler: CompletionHandler): DisposableHandle {
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300275 invokeOnCancellation(handler)
276 return NonDisposableHandle
277 }
Roman Elizarov4d626de2018-01-11 22:57:28 +0300278
Roman Elizarov1216e912017-02-22 09:57:06 +0300279 override fun tryResume(value: T, idempotent: Any?): Any? {
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300280 loopOnState { state ->
Roman Elizarov187eace2017-01-31 09:39:58 +0300281 when (state) {
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300282 is NotCompleted -> {
Roman Elizarov932e8602017-06-21 17:21:37 +0300283 val update: Any? = if (idempotent == null) value else
284 CompletedIdempotentResult(idempotent, value, state)
Vsevolod Tolstopyatovf6430f42018-04-17 17:56:32 +0300285 if (tryUpdateStateToFinal(state, update)) return state
Roman Elizarov1216e912017-02-22 09:57:06 +0300286 }
287 is CompletedIdempotentResult -> {
288 if (state.idempotentResume === idempotent) {
289 check(state.result === value) { "Non-idempotent resume" }
290 return state.token
291 } else
292 return null
293 }
Roman Elizarov7b2d8b02017-02-02 20:09:14 +0300294 else -> return null // cannot resume -- not active anymore
Roman Elizarov187eace2017-01-31 09:39:58 +0300295 }
296 }
297 }
298
Roman Elizarovf6fed2a2017-02-03 19:12:09 +0300299 override fun tryResumeWithException(exception: Throwable): Any? {
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300300 loopOnState { state ->
301 when (state) {
302 is NotCompleted -> {
Vsevolod Tolstopyatovf6430f42018-04-17 17:56:32 +0300303 if (tryUpdateStateToFinal(state, CompletedExceptionally(exception))) return state
Roman Elizarov1216e912017-02-22 09:57:06 +0300304 }
Roman Elizarovf6fed2a2017-02-03 19:12:09 +0300305 else -> return null // cannot resume -- not active anymore
306 }
307 }
308 }
309
Vsevolod Tolstopyatovf6430f42018-04-17 17:56:32 +0300310 override fun completeResume(token: Any) = completeStateUpdate(token as NotCompleted, state, resumeMode)
Roman Elizarov7b2d8b02017-02-02 20:09:14 +0300311
Roman Elizarova198bad2017-02-10 13:30:38 +0300312 override fun CoroutineDispatcher.resumeUndispatched(value: T) {
Roman Elizarov8552f0e2017-09-28 13:03:44 +0300313 val dc = delegate as? DispatchedContinuation
314 resumeImpl(value, if (dc?.dispatcher === this) MODE_UNDISPATCHED else resumeMode)
Roman Elizarova198bad2017-02-10 13:30:38 +0300315 }
316
317 override fun CoroutineDispatcher.resumeUndispatchedWithException(exception: Throwable) {
Roman Elizarov8552f0e2017-09-28 13:03:44 +0300318 val dc = delegate as? DispatchedContinuation
Roman Elizarovbcdd8e12017-10-20 16:42:06 +0800319 resumeImpl(CompletedExceptionally(exception), if (dc?.dispatcher === this) MODE_UNDISPATCHED else resumeMode)
Roman Elizarov1216e912017-02-22 09:57:06 +0300320 }
Roman Elizarov69d9c852017-07-12 15:22:21 +0300321
Roman Elizarovbcdd8e12017-10-20 16:42:06 +0800322 @Suppress("UNCHECKED_CAST")
323 override fun <T> getSuccessfulResult(state: Any?): T =
324 if (state is CompletedIdempotentResult) state.result as T else state as T
325
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300326 protected override fun nameString(): String =
Roman Elizarov8b38fa22017-09-27 17:44:31 +0300327 "CancellableContinuation(${delegate.toDebugString()})"
Roman Elizarov3754f952017-01-18 20:47:54 +0300328}
Roman Elizarove22f14a2017-06-22 19:04:52 +0300329
330private class CompletedIdempotentResult(
331 @JvmField val idempotentResume: Any?,
332 @JvmField val result: Any?,
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +0300333 @JvmField val token: NotCompleted
Roman Elizarove22f14a2017-06-22 19:04:52 +0300334) {
335 override fun toString(): String = "CompletedIdempotentResult[$result]"
336}