blob: 9c754205ac59f9e06ec2eef098a17f0d91839936 [file] [log] [blame]
Roman Elizarovf16fd272017-02-07 11:26:00 +03001/*
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 Elizarov3754f952017-01-18 20:47:54 +030017package kotlinx.coroutines.experimental
18
Roman Elizarov1216e912017-02-22 09:57:06 +030019import kotlinx.coroutines.experimental.intrinsics.startUndispatchedCoroutine
20import kotlinx.coroutines.experimental.selects.SelectBuilder
21import kotlinx.coroutines.experimental.selects.SelectInstance
Roman Elizarovea4a51b2017-01-31 12:01:25 +030022import kotlin.coroutines.experimental.CoroutineContext
23import kotlin.coroutines.experimental.startCoroutine
Roman Elizarov3754f952017-01-18 20:47:54 +030024
25/**
Roman Elizarov32d95322017-02-09 15:57:31 +030026 * Deferred value is a non-blocking cancellable future.
27 * It is created with [async] coroutine builder.
Roman Elizarov41c5c8b2017-01-25 13:37:15 +030028 * It is in [active][isActive] state while the value is being computed.
Roman Elizarovb7c46de2017-02-08 12:35:24 +030029 *
Roman Elizarov32d95322017-02-09 15:57:31 +030030 * Deferred value has four or five possible states.
Roman Elizarovb7c46de2017-02-08 12:35:24 +030031 *
Roman Elizarov32d95322017-02-09 15:57:31 +030032 * | **State** | [isActive] | [isCompleted] | [isCompletedExceptionally] | [isCancelled] |
Roman Elizarov7886ef62017-02-13 14:00:18 +030033 * | -------------------------------- | ---------- | ------------- | -------------------------- | ------------- |
Roman Elizarov32d95322017-02-09 15:57:31 +030034 * | _New_ (optional initial state) | `false` | `false` | `false` | `false` |
35 * | _Active_ (default initial state) | `true` | `false` | `false` | `false` |
36 * | _Resolved_ (final state) | `false` | `true` | `false` | `false` |
37 * | _Failed_ (final state) | `false` | `true` | `true` | `false` |
38 * | _Cancelled_ (final state) | `false` | `true` | `true` | `true` |
39 *
40 * Usually, a deferred value is created in _active_ state (it is created and started), so its only visible
41 * states are _active_ and _completed_ (_resolved_, _failed_, or _cancelled_) state.
42 * However, [async] coroutine builder has an optional `start` parameter that creates a deferred value in _new_ state
43 * when this parameter is set to `false`.
44 * Such a deferred can be be made _active_ by invoking [start], [join], or [await].
Roman Elizarov3754f952017-01-18 20:47:54 +030045 */
46public interface Deferred<out T> : Job {
47 /**
Roman Elizarovb7c46de2017-02-08 12:35:24 +030048 * Returns `true` if computation of this deferred value has _completed exceptionally_ -- it had
49 * either _failed_ with exception during computation or was [cancelled][cancel].
Roman Elizarov32d95322017-02-09 15:57:31 +030050 *
51 * It implies that [isActive] is `false` and [isCompleted] is `true`.
Roman Elizarovb7c46de2017-02-08 12:35:24 +030052 */
53 val isCompletedExceptionally: Boolean
54
55 /**
56 * Returns `true` if computation of this deferred value was [cancelled][cancel].
Roman Elizarov32d95322017-02-09 15:57:31 +030057 *
58 * It implies that [isActive] is `false`, [isCompleted] is `true`, and [isCompletedExceptionally] is `true`.
Roman Elizarovb7c46de2017-02-08 12:35:24 +030059 */
60 val isCancelled: Boolean
61
62 /**
Roman Elizarovbe4cae32017-02-15 17:57:02 +030063 * Awaits for completion of this value without blocking a thread and resumes when deferred computation is complete,
64 * returning the resulting value or throwing the corresponding exception if the deferred had completed exceptionally.
Roman Elizarov32d95322017-02-09 15:57:31 +030065 *
Roman Elizarovbe4cae32017-02-15 17:57:02 +030066 * This suspending function is cancellable.
Roman Elizarov3754f952017-01-18 20:47:54 +030067 * If the [Job] of the current coroutine is completed while this suspending function is waiting, this function
Roman Elizarovc5814542017-01-19 10:19:06 +030068 * immediately resumes with [CancellationException].
Roman Elizarov3754f952017-01-18 20:47:54 +030069 */
70 public suspend fun await(): T
Roman Elizarovc5814542017-01-19 10:19:06 +030071
72 /**
Roman Elizarov1216e912017-02-22 09:57:06 +030073 * Registers [onAwait][SelectBuilder.onAwait] select clause.
74 * @suppress **This is unstable API and it is subject to change.**
75 */
76 public fun <R> registerSelectAwait(select: SelectInstance<R>, block: suspend (T) -> R)
77
78 /**
Roman Elizarov32d95322017-02-09 15:57:31 +030079 * Returns *completed* result or throws [IllegalStateException] if this deferred value has not
80 * [completed][isCompleted] yet. It throws the corresponding exception if this deferred has
81 * [completed exceptionally][isCompletedExceptionally].
82 *
Roman Elizarove7803472017-02-16 09:52:31 +030083 * This function is designed to be used from [invokeOnCompletion] handlers, when there is an absolute certainty that
Roman Elizarovc5814542017-01-19 10:19:06 +030084 * the value is already complete.
85 */
86 public fun getCompleted(): T
Roman Elizarov32d95322017-02-09 15:57:31 +030087
88 /**
Roman Elizarovfc7a9a22017-02-13 11:54:01 +030089 * @suppress **Deprecated**: Use `isActive`.
Roman Elizarov32d95322017-02-09 15:57:31 +030090 */
91 @Deprecated(message = "Use `isActive`", replaceWith = ReplaceWith("isActive"))
92 public val isComputing: Boolean get() = isActive
Roman Elizarov3754f952017-01-18 20:47:54 +030093}
94
95/**
Roman Elizarov32d95322017-02-09 15:57:31 +030096 * Creates new coroutine and returns its future result as an implementation of [Deferred].
Roman Elizarov44ba4b12017-01-25 11:37:54 +030097 *
Roman Elizarov32d95322017-02-09 15:57:31 +030098 * The running coroutine is cancelled when the resulting object is [cancelled][Job.cancel].
Roman Elizarov44ba4b12017-01-25 11:37:54 +030099 * The [context] for the new coroutine must be explicitly specified.
Roman Elizaroved7b8642017-01-19 11:22:28 +0300100 * See [CoroutineDispatcher] for the standard [context] implementations that are provided by `kotlinx.coroutines`.
Roman Elizarov44ba4b12017-01-25 11:37:54 +0300101 * The [context][CoroutineScope.context] of the parent coroutine from its [scope][CoroutineScope] may be used,
102 * in which case the [Job] of the resulting coroutine is a child of the job of the parent coroutine.
Roman Elizarov32d95322017-02-09 15:57:31 +0300103 *
104 * An optional [start] parameter can be set to `false` to start coroutine _lazily_. When `start = false`,
105 * the resulting [Deferred] is created in _new_ state. It can be explicitly started with [start][Job.start]
106 * function and will be started implicitly on the first invocation of [join][Job.join] or [await][Deferred.await].
107 *
108 * By default, the coroutine is immediately started. Set an optional [start] parameters to `false`
109 * to create coroutine without starting it. In this case it will be _lazy_ and will start
Roman Elizarov3754f952017-01-18 20:47:54 +0300110 */
Roman Elizarov32d95322017-02-09 15:57:31 +0300111public fun <T> async(context: CoroutineContext, start: Boolean = true, block: suspend CoroutineScope.() -> T) : Deferred<T> {
112 val newContext = newCoroutineContext(context)
113 val coroutine = if (start)
114 DeferredCoroutine<T>(newContext, active = true) else
115 LazyDeferredCoroutine(newContext, block)
116 coroutine.initParentJob(context[Job])
117 if (start) block.startCoroutine(coroutine, coroutine)
118 return coroutine
119}
120
121/**
Roman Elizarovfc7a9a22017-02-13 11:54:01 +0300122 * @suppress **Deprecated**: `defer` was renamed to `async`.
Roman Elizarov32d95322017-02-09 15:57:31 +0300123 */
124@Deprecated(message = "`defer` was renamed to `async`", level = DeprecationLevel.WARNING,
125 replaceWith = ReplaceWith("async(context, block = block)"))
Roman Elizarovd528e3e2017-01-23 15:40:05 +0300126public fun <T> defer(context: CoroutineContext, block: suspend CoroutineScope.() -> T) : Deferred<T> =
Roman Elizarov32d95322017-02-09 15:57:31 +0300127 async(context, block = block)
Roman Elizarov3754f952017-01-18 20:47:54 +0300128
Roman Elizarov32d95322017-02-09 15:57:31 +0300129private open class DeferredCoroutine<T>(
Roman Elizarov1216e912017-02-22 09:57:06 +0300130 override val parentContext: CoroutineContext,
Roman Elizarov32d95322017-02-09 15:57:31 +0300131 active: Boolean
Roman Elizarov1216e912017-02-22 09:57:06 +0300132) : AbstractCoroutine<T>(active), Deferred<T> {
Roman Elizarovee7c0eb2017-02-16 15:29:28 +0300133 override val isCompletedExceptionally: Boolean get() = state is CompletedExceptionally
134 override val isCancelled: Boolean get() = state is Cancelled
Roman Elizarovb7c46de2017-02-08 12:35:24 +0300135
Roman Elizarov3754f952017-01-18 20:47:54 +0300136 @Suppress("UNCHECKED_CAST")
137 suspend override fun await(): T {
Roman Elizarov32d95322017-02-09 15:57:31 +0300138 // fast-path -- check state (avoid extra object creation)
139 while(true) { // lock-free loop on state
Roman Elizarovee7c0eb2017-02-16 15:29:28 +0300140 val state = this.state
Roman Elizarov32d95322017-02-09 15:57:31 +0300141 if (state !is Incomplete) {
142 // already complete -- just return result
Roman Elizarov41c5c8b2017-01-25 13:37:15 +0300143 if (state is CompletedExceptionally) throw state.exception
144 return state as T
Roman Elizarov32d95322017-02-09 15:57:31 +0300145
Roman Elizarov41c5c8b2017-01-25 13:37:15 +0300146 }
Roman Elizarov32d95322017-02-09 15:57:31 +0300147 if (startInternal(state) >= 0) break // break unless needs to retry
Roman Elizarov41c5c8b2017-01-25 13:37:15 +0300148 }
Roman Elizarov32d95322017-02-09 15:57:31 +0300149 return awaitSuspend() // slow-path
Roman Elizarov3754f952017-01-18 20:47:54 +0300150 }
151
152 @Suppress("UNCHECKED_CAST")
Roman Elizarov32d95322017-02-09 15:57:31 +0300153 private suspend fun awaitSuspend(): T = suspendCancellableCoroutine { cont ->
Roman Elizarove7803472017-02-16 09:52:31 +0300154 cont.unregisterOnCompletion(invokeOnCompletion {
Roman Elizarovee7c0eb2017-02-16 15:29:28 +0300155 val state = this.state
Roman Elizarov32d95322017-02-09 15:57:31 +0300156 check(state !is Incomplete)
Roman Elizarov3754f952017-01-18 20:47:54 +0300157 if (state is CompletedExceptionally)
158 cont.resumeWithException(state.exception)
159 else
160 cont.resume(state as T)
161 })
162 }
163
Roman Elizarov1216e912017-02-22 09:57:06 +0300164 override fun <R> registerSelectAwait(select: SelectInstance<R>, block: suspend (T) -> R) {
165 if (select.isSelected) return
166 val state = this.state
167 if (state is Incomplete) {
168 select.unregisterOnCompletion(invokeOnCompletion(SelectOnCompletion(this, select, block)))
169 } else
170 selectCompletion(select, block, state)
171 }
172
173 @Suppress("UNCHECKED_CAST")
174 internal fun <R> selectCompletion(select: SelectInstance<R>, block: suspend (T) -> R, state: Any? = this.state) {
175 if (select.trySelect(idempotent = null)) {
176 if (state is CompletedExceptionally)
177 select.resumeSelectWithException(state.exception)
178 else
179 block.startUndispatchedCoroutine(state as T, select.completion)
180 }
181 }
182
Roman Elizarovc5814542017-01-19 10:19:06 +0300183 @Suppress("UNCHECKED_CAST")
184 override fun getCompleted(): T {
Roman Elizarovee7c0eb2017-02-16 15:29:28 +0300185 val state = this.state
Roman Elizarov32d95322017-02-09 15:57:31 +0300186 check(state !is Incomplete) { "This deferred value has not completed yet" }
Roman Elizarovc5814542017-01-19 10:19:06 +0300187 if (state is CompletedExceptionally) throw state.exception
188 return state as T
Roman Elizarov3754f952017-01-18 20:47:54 +0300189 }
Roman Elizarov32d95322017-02-09 15:57:31 +0300190}
191
Roman Elizarov1216e912017-02-22 09:57:06 +0300192private class SelectOnCompletion<T, R>(
193 deferred: DeferredCoroutine<T>,
194 private val select: SelectInstance<R>,
195 private val block: suspend (T) -> R
196) : JobNode<DeferredCoroutine<T>>(deferred) {
197 override fun invoke(reason: Throwable?) = job.selectCompletion(select, block)
198 override fun toString(): String = "SelectOnCompletion[$select]"
199}
200
Roman Elizarov32d95322017-02-09 15:57:31 +0300201private class LazyDeferredCoroutine<T>(
Roman Elizarov1216e912017-02-22 09:57:06 +0300202 parentContext: CoroutineContext,
203 private val block: suspend CoroutineScope.() -> T
204) : DeferredCoroutine<T>(parentContext, active = false) {
Roman Elizarov32d95322017-02-09 15:57:31 +0300205 override fun onStart() {
206 block.startCoroutine(this, this)
207 }
Roman Elizarov3754f952017-01-18 20:47:54 +0300208}