blob: c3954d346db653b43615560e7f41e2f2174bbdc5 [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 Elizarovea4a51b2017-01-31 12:01:25 +030019import kotlin.coroutines.experimental.CoroutineContext
20import kotlin.coroutines.experimental.startCoroutine
Roman Elizarov3754f952017-01-18 20:47:54 +030021
22/**
Roman Elizarov32d95322017-02-09 15:57:31 +030023 * Deferred value is a non-blocking cancellable future.
24 * It is created with [async] coroutine builder.
Roman Elizarov41c5c8b2017-01-25 13:37:15 +030025 * It is in [active][isActive] state while the value is being computed.
Roman Elizarovb7c46de2017-02-08 12:35:24 +030026 *
Roman Elizarov32d95322017-02-09 15:57:31 +030027 * Deferred value has four or five possible states.
Roman Elizarovb7c46de2017-02-08 12:35:24 +030028 *
Roman Elizarov32d95322017-02-09 15:57:31 +030029 * | **State** | [isActive] | [isCompleted] | [isCompletedExceptionally] | [isCancelled] |
Roman Elizarov7886ef62017-02-13 14:00:18 +030030 * | -------------------------------- | ---------- | ------------- | -------------------------- | ------------- |
Roman Elizarov32d95322017-02-09 15:57:31 +030031 * | _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 Elizarov3754f952017-01-18 20:47:54 +030042 */
43public interface Deferred<out T> : Job {
44 /**
Roman Elizarovb7c46de2017-02-08 12:35:24 +030045 * 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 Elizarov32d95322017-02-09 15:57:31 +030047 *
48 * It implies that [isActive] is `false` and [isCompleted] is `true`.
Roman Elizarovb7c46de2017-02-08 12:35:24 +030049 */
50 val isCompletedExceptionally: Boolean
51
52 /**
53 * Returns `true` if computation of this deferred value was [cancelled][cancel].
Roman Elizarov32d95322017-02-09 15:57:31 +030054 *
55 * It implies that [isActive] is `false`, [isCompleted] is `true`, and [isCompletedExceptionally] is `true`.
Roman Elizarovb7c46de2017-02-08 12:35:24 +030056 */
57 val isCancelled: Boolean
58
59 /**
Roman Elizarovbe4cae32017-02-15 17:57:02 +030060 * Awaits for completion of this value without blocking a thread and resumes when deferred computation is complete,
61 * returning the resulting value or throwing the corresponding exception if the deferred had completed exceptionally.
Roman Elizarov32d95322017-02-09 15:57:31 +030062 *
Roman Elizarovbe4cae32017-02-15 17:57:02 +030063 * This suspending function is cancellable.
Roman Elizarov3754f952017-01-18 20:47:54 +030064 * If the [Job] of the current coroutine is completed while this suspending function is waiting, this function
Roman Elizarovc5814542017-01-19 10:19:06 +030065 * immediately resumes with [CancellationException].
Roman Elizarov3754f952017-01-18 20:47:54 +030066 */
67 public suspend fun await(): T
Roman Elizarovc5814542017-01-19 10:19:06 +030068
69 /**
Roman Elizarov32d95322017-02-09 15:57:31 +030070 * Returns *completed* result or throws [IllegalStateException] if this deferred value has not
71 * [completed][isCompleted] yet. It throws the corresponding exception if this deferred has
72 * [completed exceptionally][isCompletedExceptionally].
73 *
Roman Elizarove7803472017-02-16 09:52:31 +030074 * This function is designed to be used from [invokeOnCompletion] handlers, when there is an absolute certainty that
Roman Elizarovc5814542017-01-19 10:19:06 +030075 * the value is already complete.
76 */
77 public fun getCompleted(): T
Roman Elizarov32d95322017-02-09 15:57:31 +030078
79 /**
Roman Elizarovfc7a9a22017-02-13 11:54:01 +030080 * @suppress **Deprecated**: Use `isActive`.
Roman Elizarov32d95322017-02-09 15:57:31 +030081 */
82 @Deprecated(message = "Use `isActive`", replaceWith = ReplaceWith("isActive"))
83 public val isComputing: Boolean get() = isActive
Roman Elizarov3754f952017-01-18 20:47:54 +030084}
85
86/**
Roman Elizarov32d95322017-02-09 15:57:31 +030087 * Creates new coroutine and returns its future result as an implementation of [Deferred].
Roman Elizarov44ba4b12017-01-25 11:37:54 +030088 *
Roman Elizarov32d95322017-02-09 15:57:31 +030089 * The running coroutine is cancelled when the resulting object is [cancelled][Job.cancel].
Roman Elizarov44ba4b12017-01-25 11:37:54 +030090 * The [context] for the new coroutine must be explicitly specified.
Roman Elizaroved7b8642017-01-19 11:22:28 +030091 * See [CoroutineDispatcher] for the standard [context] implementations that are provided by `kotlinx.coroutines`.
Roman Elizarov44ba4b12017-01-25 11:37:54 +030092 * The [context][CoroutineScope.context] of the parent coroutine from its [scope][CoroutineScope] may be used,
93 * 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 +030094 *
95 * An optional [start] parameter can be set to `false` to start coroutine _lazily_. When `start = false`,
96 * the resulting [Deferred] is created in _new_ state. It can be explicitly started with [start][Job.start]
97 * function and will be started implicitly on the first invocation of [join][Job.join] or [await][Deferred.await].
98 *
99 * By default, the coroutine is immediately started. Set an optional [start] parameters to `false`
100 * to create coroutine without starting it. In this case it will be _lazy_ and will start
Roman Elizarov3754f952017-01-18 20:47:54 +0300101 */
Roman Elizarov32d95322017-02-09 15:57:31 +0300102public fun <T> async(context: CoroutineContext, start: Boolean = true, block: suspend CoroutineScope.() -> T) : Deferred<T> {
103 val newContext = newCoroutineContext(context)
104 val coroutine = if (start)
105 DeferredCoroutine<T>(newContext, active = true) else
106 LazyDeferredCoroutine(newContext, block)
107 coroutine.initParentJob(context[Job])
108 if (start) block.startCoroutine(coroutine, coroutine)
109 return coroutine
110}
111
112/**
Roman Elizarovfc7a9a22017-02-13 11:54:01 +0300113 * @suppress **Deprecated**: `defer` was renamed to `async`.
Roman Elizarov32d95322017-02-09 15:57:31 +0300114 */
115@Deprecated(message = "`defer` was renamed to `async`", level = DeprecationLevel.WARNING,
116 replaceWith = ReplaceWith("async(context, block = block)"))
Roman Elizarovd528e3e2017-01-23 15:40:05 +0300117public fun <T> defer(context: CoroutineContext, block: suspend CoroutineScope.() -> T) : Deferred<T> =
Roman Elizarov32d95322017-02-09 15:57:31 +0300118 async(context, block = block)
Roman Elizarov3754f952017-01-18 20:47:54 +0300119
Roman Elizarov32d95322017-02-09 15:57:31 +0300120private open class DeferredCoroutine<T>(
121 context: CoroutineContext,
122 active: Boolean
123) : AbstractCoroutine<T>(context, active), Deferred<T> {
Roman Elizarovb7c46de2017-02-08 12:35:24 +0300124 override val isCompletedExceptionally: Boolean get() = getState() is CompletedExceptionally
125 override val isCancelled: Boolean get() = getState() is Cancelled
126
Roman Elizarov3754f952017-01-18 20:47:54 +0300127 @Suppress("UNCHECKED_CAST")
128 suspend override fun await(): T {
Roman Elizarov32d95322017-02-09 15:57:31 +0300129 // fast-path -- check state (avoid extra object creation)
130 while(true) { // lock-free loop on state
131 val state = this.getState()
132 if (state !is Incomplete) {
133 // already complete -- just return result
Roman Elizarov41c5c8b2017-01-25 13:37:15 +0300134 if (state is CompletedExceptionally) throw state.exception
135 return state as T
Roman Elizarov32d95322017-02-09 15:57:31 +0300136
Roman Elizarov41c5c8b2017-01-25 13:37:15 +0300137 }
Roman Elizarov32d95322017-02-09 15:57:31 +0300138 if (startInternal(state) >= 0) break // break unless needs to retry
Roman Elizarov41c5c8b2017-01-25 13:37:15 +0300139 }
Roman Elizarov32d95322017-02-09 15:57:31 +0300140 return awaitSuspend() // slow-path
Roman Elizarov3754f952017-01-18 20:47:54 +0300141 }
142
143 @Suppress("UNCHECKED_CAST")
Roman Elizarov32d95322017-02-09 15:57:31 +0300144 private suspend fun awaitSuspend(): T = suspendCancellableCoroutine { cont ->
Roman Elizarove7803472017-02-16 09:52:31 +0300145 cont.unregisterOnCompletion(invokeOnCompletion {
Roman Elizarov3754f952017-01-18 20:47:54 +0300146 val state = getState()
Roman Elizarov32d95322017-02-09 15:57:31 +0300147 check(state !is Incomplete)
Roman Elizarov3754f952017-01-18 20:47:54 +0300148 if (state is CompletedExceptionally)
149 cont.resumeWithException(state.exception)
150 else
151 cont.resume(state as T)
152 })
153 }
154
Roman Elizarovc5814542017-01-19 10:19:06 +0300155 @Suppress("UNCHECKED_CAST")
156 override fun getCompleted(): T {
157 val state = getState()
Roman Elizarov32d95322017-02-09 15:57:31 +0300158 check(state !is Incomplete) { "This deferred value has not completed yet" }
Roman Elizarovc5814542017-01-19 10:19:06 +0300159 if (state is CompletedExceptionally) throw state.exception
160 return state as T
Roman Elizarov3754f952017-01-18 20:47:54 +0300161 }
Roman Elizarov32d95322017-02-09 15:57:31 +0300162}
163
164private class LazyDeferredCoroutine<T>(
165 context: CoroutineContext,
166 val block: suspend CoroutineScope.() -> T
167) : DeferredCoroutine<T>(context, active = false) {
168 override fun onStart() {
169 block.startCoroutine(this, this)
170 }
Roman Elizarov3754f952017-01-18 20:47:54 +0300171}