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] | |
Roman Elizarov | 7886ef6 | 2017-02-13 14:00:18 +0300 | [diff] [blame^] | 30 | * | -------------------------------- | ---------- | ------------- | -------------------------- | ------------- | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 31 | * | _New_ (optional initial state) | `false` | `false` | `false` | `false` | |
| 32 | * | _Active_ (default initial state) | `true` | `false` | `false` | `false` | |
| 33 | * | _Resolved_ (final state) | `false` | `true` | `false` | `false` | |
| 34 | * | _Failed_ (final state) | `false` | `true` | `true` | `false` | |
| 35 | * | _Cancelled_ (final state) | `false` | `true` | `true` | `true` | |
| 36 | * |
| 37 | * Usually, a deferred value is created in _active_ state (it is created and started), so its only visible |
| 38 | * states are _active_ and _completed_ (_resolved_, _failed_, or _cancelled_) state. |
| 39 | * However, [async] coroutine builder has an optional `start` parameter that creates a deferred value in _new_ state |
| 40 | * when this parameter is set to `false`. |
| 41 | * 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] | 42 | */ |
| 43 | public interface Deferred<out T> : Job { |
| 44 | /** |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 45 | * Returns `true` if computation of this deferred value has _completed exceptionally_ -- it had |
| 46 | * either _failed_ with exception during computation or was [cancelled][cancel]. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 47 | * |
| 48 | * It implies that [isActive] is `false` and [isCompleted] is `true`. |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 49 | */ |
| 50 | val isCompletedExceptionally: Boolean |
| 51 | |
| 52 | /** |
| 53 | * Returns `true` if computation of this deferred value was [cancelled][cancel]. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 54 | * |
| 55 | * 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] | 56 | */ |
| 57 | val isCancelled: Boolean |
| 58 | |
| 59 | /** |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 60 | * Awaits for completion of this value without blocking a thread and resumes when deferred computation is complete. |
| 61 | * This suspending function is cancellable. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 62 | * |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 63 | * 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] | 64 | * immediately resumes with [CancellationException]. |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 65 | */ |
| 66 | public suspend fun await(): T |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 67 | |
| 68 | /** |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 69 | * Returns *completed* result or throws [IllegalStateException] if this deferred value has not |
| 70 | * [completed][isCompleted] yet. It throws the corresponding exception if this deferred has |
| 71 | * [completed exceptionally][isCompletedExceptionally]. |
| 72 | * |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 73 | * This function is designed to be used from [onCompletion] handlers, when there is an absolute certainty that |
| 74 | * the value is already complete. |
| 75 | */ |
| 76 | public fun getCompleted(): T |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 77 | |
| 78 | /** |
Roman Elizarov | fc7a9a2 | 2017-02-13 11:54:01 +0300 | [diff] [blame] | 79 | * @suppress **Deprecated**: Use `isActive`. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 80 | */ |
| 81 | @Deprecated(message = "Use `isActive`", replaceWith = ReplaceWith("isActive")) |
| 82 | public val isComputing: Boolean get() = isActive |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 83 | } |
| 84 | |
| 85 | /** |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 86 | * 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] | 87 | * |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 88 | * 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] | 89 | * The [context] for the new coroutine must be explicitly specified. |
Roman Elizarov | ed7b864 | 2017-01-19 11:22:28 +0300 | [diff] [blame] | 90 | * 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] | 91 | * The [context][CoroutineScope.context] of the parent coroutine from its [scope][CoroutineScope] may be used, |
| 92 | * 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] | 93 | * |
| 94 | * An optional [start] parameter can be set to `false` to start coroutine _lazily_. When `start = false`, |
| 95 | * the resulting [Deferred] is created in _new_ state. It can be explicitly started with [start][Job.start] |
| 96 | * function and will be started implicitly on the first invocation of [join][Job.join] or [await][Deferred.await]. |
| 97 | * |
| 98 | * By default, the coroutine is immediately started. Set an optional [start] parameters to `false` |
| 99 | * 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] | 100 | */ |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 101 | public fun <T> async(context: CoroutineContext, start: Boolean = true, block: suspend CoroutineScope.() -> T) : Deferred<T> { |
| 102 | val newContext = newCoroutineContext(context) |
| 103 | val coroutine = if (start) |
| 104 | DeferredCoroutine<T>(newContext, active = true) else |
| 105 | LazyDeferredCoroutine(newContext, block) |
| 106 | coroutine.initParentJob(context[Job]) |
| 107 | if (start) block.startCoroutine(coroutine, coroutine) |
| 108 | return coroutine |
| 109 | } |
| 110 | |
| 111 | /** |
Roman Elizarov | fc7a9a2 | 2017-02-13 11:54:01 +0300 | [diff] [blame] | 112 | * @suppress **Deprecated**: `defer` was renamed to `async`. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 113 | */ |
| 114 | @Deprecated(message = "`defer` was renamed to `async`", level = DeprecationLevel.WARNING, |
| 115 | replaceWith = ReplaceWith("async(context, block = block)")) |
Roman Elizarov | d528e3e | 2017-01-23 15:40:05 +0300 | [diff] [blame] | 116 | public fun <T> defer(context: CoroutineContext, block: suspend CoroutineScope.() -> T) : Deferred<T> = |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 117 | async(context, block = block) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 118 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 119 | private open class DeferredCoroutine<T>( |
| 120 | context: CoroutineContext, |
| 121 | active: Boolean |
| 122 | ) : AbstractCoroutine<T>(context, active), Deferred<T> { |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 123 | override val isCompletedExceptionally: Boolean get() = getState() is CompletedExceptionally |
| 124 | override val isCancelled: Boolean get() = getState() is Cancelled |
| 125 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 126 | @Suppress("UNCHECKED_CAST") |
| 127 | suspend override fun await(): T { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 128 | // fast-path -- check state (avoid extra object creation) |
| 129 | while(true) { // lock-free loop on state |
| 130 | val state = this.getState() |
| 131 | if (state !is Incomplete) { |
| 132 | // already complete -- just return result |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 133 | if (state is CompletedExceptionally) throw state.exception |
| 134 | return state as T |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 135 | |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 136 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 137 | if (startInternal(state) >= 0) break // break unless needs to retry |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 138 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 139 | return awaitSuspend() // slow-path |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 140 | } |
| 141 | |
| 142 | @Suppress("UNCHECKED_CAST") |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 143 | private suspend fun awaitSuspend(): T = suspendCancellableCoroutine { cont -> |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 144 | cont.unregisterOnCompletion(onCompletion { |
| 145 | val state = getState() |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 146 | check(state !is Incomplete) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 147 | if (state is CompletedExceptionally) |
| 148 | cont.resumeWithException(state.exception) |
| 149 | else |
| 150 | cont.resume(state as T) |
| 151 | }) |
| 152 | } |
| 153 | |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 154 | @Suppress("UNCHECKED_CAST") |
| 155 | override fun getCompleted(): T { |
| 156 | val state = getState() |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 157 | check(state !is Incomplete) { "This deferred value has not completed yet" } |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 158 | if (state is CompletedExceptionally) throw state.exception |
| 159 | return state as T |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 160 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 161 | } |
| 162 | |
| 163 | private class LazyDeferredCoroutine<T>( |
| 164 | context: CoroutineContext, |
| 165 | val block: suspend CoroutineScope.() -> T |
| 166 | ) : DeferredCoroutine<T>(context, active = false) { |
| 167 | override fun onStart() { |
| 168 | block.startCoroutine(this, this) |
| 169 | } |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 170 | } |