Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2016-2017 JetBrains s.r.o. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 17 | package kotlinx.coroutines.experimental |
| 18 | |
Roman Elizarov | ea4a51b | 2017-01-31 12:01:25 +0300 | [diff] [blame] | 19 | import kotlin.coroutines.experimental.CoroutineContext |
| 20 | import kotlin.coroutines.experimental.startCoroutine |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 21 | |
| 22 | /** |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 23 | * Deferred value is a non-blocking cancellable future. |
| 24 | * It is created with [async] coroutine builder. |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 25 | * It is in [active][isActive] state while the value is being computed. |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 26 | * |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 27 | * Deferred value has four or five possible states. |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 28 | * |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 29 | * | **State** | [isActive] | [isCompleted] | [isCompletedExceptionally] | [isCancelled] | |
| 30 | * | _New_ (optional initial state) | `false` | `false` | `false` | `false` | |
| 31 | * | _Active_ (default initial state) | `true` | `false` | `false` | `false` | |
| 32 | * | _Resolved_ (final state) | `false` | `true` | `false` | `false` | |
| 33 | * | _Failed_ (final state) | `false` | `true` | `true` | `false` | |
| 34 | * | _Cancelled_ (final state) | `false` | `true` | `true` | `true` | |
| 35 | * |
| 36 | * Usually, a deferred value is created in _active_ state (it is created and started), so its only visible |
| 37 | * states are _active_ and _completed_ (_resolved_, _failed_, or _cancelled_) state. |
| 38 | * However, [async] coroutine builder has an optional `start` parameter that creates a deferred value in _new_ state |
| 39 | * when this parameter is set to `false`. |
| 40 | * Such a deferred can be be made _active_ by invoking [start], [join], or [await]. |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 41 | */ |
| 42 | public interface Deferred<out T> : Job { |
| 43 | /** |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 44 | * Returns `true` if computation of this deferred value has _completed exceptionally_ -- it had |
| 45 | * either _failed_ with exception during computation or was [cancelled][cancel]. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 46 | * |
| 47 | * It implies that [isActive] is `false` and [isCompleted] is `true`. |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 48 | */ |
| 49 | val isCompletedExceptionally: Boolean |
| 50 | |
| 51 | /** |
| 52 | * Returns `true` if computation of this deferred value was [cancelled][cancel]. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 53 | * |
| 54 | * It implies that [isActive] is `false`, [isCompleted] is `true`, and [isCompletedExceptionally] is `true`. |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 55 | */ |
| 56 | val isCancelled: Boolean |
| 57 | |
| 58 | /** |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 59 | * Awaits for completion of this value without blocking a thread and resumes when deferred computation is complete. |
| 60 | * This suspending function is cancellable. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 61 | * |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 62 | * If the [Job] of the current coroutine is completed while this suspending function is waiting, this function |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 63 | * immediately resumes with [CancellationException]. |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 64 | */ |
| 65 | public suspend fun await(): T |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 66 | |
| 67 | /** |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 68 | * Returns *completed* result or throws [IllegalStateException] if this deferred value has not |
| 69 | * [completed][isCompleted] yet. It throws the corresponding exception if this deferred has |
| 70 | * [completed exceptionally][isCompletedExceptionally]. |
| 71 | * |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 72 | * This function is designed to be used from [onCompletion] handlers, when there is an absolute certainty that |
| 73 | * the value is already complete. |
| 74 | */ |
| 75 | public fun getCompleted(): T |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 76 | |
| 77 | /** |
Roman Elizarov | fc7a9a2 | 2017-02-13 11:54:01 +0300 | [diff] [blame] | 78 | * @suppress **Deprecated**: Use `isActive`. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 79 | */ |
| 80 | @Deprecated(message = "Use `isActive`", replaceWith = ReplaceWith("isActive")) |
| 81 | public val isComputing: Boolean get() = isActive |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 82 | } |
| 83 | |
| 84 | /** |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 85 | * Creates new coroutine and returns its future result as an implementation of [Deferred]. |
Roman Elizarov | 44ba4b1 | 2017-01-25 11:37:54 +0300 | [diff] [blame] | 86 | * |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 87 | * The running coroutine is cancelled when the resulting object is [cancelled][Job.cancel]. |
Roman Elizarov | 44ba4b1 | 2017-01-25 11:37:54 +0300 | [diff] [blame] | 88 | * The [context] for the new coroutine must be explicitly specified. |
Roman Elizarov | ed7b864 | 2017-01-19 11:22:28 +0300 | [diff] [blame] | 89 | * See [CoroutineDispatcher] for the standard [context] implementations that are provided by `kotlinx.coroutines`. |
Roman Elizarov | 44ba4b1 | 2017-01-25 11:37:54 +0300 | [diff] [blame] | 90 | * The [context][CoroutineScope.context] of the parent coroutine from its [scope][CoroutineScope] may be used, |
| 91 | * in which case the [Job] of the resulting coroutine is a child of the job of the parent coroutine. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 92 | * |
| 93 | * An optional [start] parameter can be set to `false` to start coroutine _lazily_. When `start = false`, |
| 94 | * the resulting [Deferred] is created in _new_ state. It can be explicitly started with [start][Job.start] |
| 95 | * function and will be started implicitly on the first invocation of [join][Job.join] or [await][Deferred.await]. |
| 96 | * |
| 97 | * By default, the coroutine is immediately started. Set an optional [start] parameters to `false` |
| 98 | * to create coroutine without starting it. In this case it will be _lazy_ and will start |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 99 | */ |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 100 | public fun <T> async(context: CoroutineContext, start: Boolean = true, block: suspend CoroutineScope.() -> T) : Deferred<T> { |
| 101 | val newContext = newCoroutineContext(context) |
| 102 | val coroutine = if (start) |
| 103 | DeferredCoroutine<T>(newContext, active = true) else |
| 104 | LazyDeferredCoroutine(newContext, block) |
| 105 | coroutine.initParentJob(context[Job]) |
| 106 | if (start) block.startCoroutine(coroutine, coroutine) |
| 107 | return coroutine |
| 108 | } |
| 109 | |
| 110 | /** |
Roman Elizarov | fc7a9a2 | 2017-02-13 11:54:01 +0300 | [diff] [blame] | 111 | * @suppress **Deprecated**: `defer` was renamed to `async`. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 112 | */ |
| 113 | @Deprecated(message = "`defer` was renamed to `async`", level = DeprecationLevel.WARNING, |
| 114 | replaceWith = ReplaceWith("async(context, block = block)")) |
Roman Elizarov | d528e3e | 2017-01-23 15:40:05 +0300 | [diff] [blame] | 115 | public fun <T> defer(context: CoroutineContext, block: suspend CoroutineScope.() -> T) : Deferred<T> = |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 116 | async(context, block = block) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 117 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 118 | private open class DeferredCoroutine<T>( |
| 119 | context: CoroutineContext, |
| 120 | active: Boolean |
| 121 | ) : AbstractCoroutine<T>(context, active), Deferred<T> { |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 122 | override val isCompletedExceptionally: Boolean get() = getState() is CompletedExceptionally |
| 123 | override val isCancelled: Boolean get() = getState() is Cancelled |
| 124 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 125 | @Suppress("UNCHECKED_CAST") |
| 126 | suspend override fun await(): T { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 127 | // fast-path -- check state (avoid extra object creation) |
| 128 | while(true) { // lock-free loop on state |
| 129 | val state = this.getState() |
| 130 | if (state !is Incomplete) { |
| 131 | // already complete -- just return result |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 132 | if (state is CompletedExceptionally) throw state.exception |
| 133 | return state as T |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 134 | |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 135 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 136 | if (startInternal(state) >= 0) break // break unless needs to retry |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 137 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 138 | return awaitSuspend() // slow-path |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 139 | } |
| 140 | |
| 141 | @Suppress("UNCHECKED_CAST") |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 142 | private suspend fun awaitSuspend(): T = suspendCancellableCoroutine { cont -> |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 143 | cont.unregisterOnCompletion(onCompletion { |
| 144 | val state = getState() |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 145 | check(state !is Incomplete) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 146 | if (state is CompletedExceptionally) |
| 147 | cont.resumeWithException(state.exception) |
| 148 | else |
| 149 | cont.resume(state as T) |
| 150 | }) |
| 151 | } |
| 152 | |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 153 | @Suppress("UNCHECKED_CAST") |
| 154 | override fun getCompleted(): T { |
| 155 | val state = getState() |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 156 | check(state !is Incomplete) { "This deferred value has not completed yet" } |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 157 | if (state is CompletedExceptionally) throw state.exception |
| 158 | return state as T |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 159 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 160 | } |
| 161 | |
| 162 | private class LazyDeferredCoroutine<T>( |
| 163 | context: CoroutineContext, |
| 164 | val block: suspend CoroutineScope.() -> T |
| 165 | ) : DeferredCoroutine<T>(context, active = false) { |
| 166 | override fun onStart() { |
| 167 | block.startCoroutine(this, this) |
| 168 | } |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 169 | } |