blob: 515da4d747f2ec002ef75f26349040788cd63cee [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] |
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 Elizarov3754f952017-01-18 20:47:54 +030041 */
42public interface Deferred<out T> : Job {
43 /**
Roman Elizarovb7c46de2017-02-08 12:35:24 +030044 * 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 Elizarov32d95322017-02-09 15:57:31 +030046 *
47 * It implies that [isActive] is `false` and [isCompleted] is `true`.
Roman Elizarovb7c46de2017-02-08 12:35:24 +030048 */
49 val isCompletedExceptionally: Boolean
50
51 /**
52 * Returns `true` if computation of this deferred value was [cancelled][cancel].
Roman Elizarov32d95322017-02-09 15:57:31 +030053 *
54 * It implies that [isActive] is `false`, [isCompleted] is `true`, and [isCompletedExceptionally] is `true`.
Roman Elizarovb7c46de2017-02-08 12:35:24 +030055 */
56 val isCancelled: Boolean
57
58 /**
Roman Elizarov3754f952017-01-18 20:47:54 +030059 * Awaits for completion of this value without blocking a thread and resumes when deferred computation is complete.
60 * This suspending function is cancellable.
Roman Elizarov32d95322017-02-09 15:57:31 +030061 *
Roman Elizarov3754f952017-01-18 20:47:54 +030062 * If the [Job] of the current coroutine is completed while this suspending function is waiting, this function
Roman Elizarovc5814542017-01-19 10:19:06 +030063 * immediately resumes with [CancellationException].
Roman Elizarov3754f952017-01-18 20:47:54 +030064 */
65 public suspend fun await(): T
Roman Elizarovc5814542017-01-19 10:19:06 +030066
67 /**
Roman Elizarov32d95322017-02-09 15:57:31 +030068 * 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 Elizarovc5814542017-01-19 10:19:06 +030072 * 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 Elizarov32d95322017-02-09 15:57:31 +030076
77 /**
78 * **Deprecated**: Use `isActive`.
79 */
80 @Deprecated(message = "Use `isActive`", replaceWith = ReplaceWith("isActive"))
81 public val isComputing: Boolean get() = isActive
Roman Elizarov3754f952017-01-18 20:47:54 +030082}
83
84/**
Roman Elizarov32d95322017-02-09 15:57:31 +030085 * Creates new coroutine and returns its future result as an implementation of [Deferred].
Roman Elizarov44ba4b12017-01-25 11:37:54 +030086 *
Roman Elizarov32d95322017-02-09 15:57:31 +030087 * The running coroutine is cancelled when the resulting object is [cancelled][Job.cancel].
Roman Elizarov44ba4b12017-01-25 11:37:54 +030088 * The [context] for the new coroutine must be explicitly specified.
Roman Elizaroved7b8642017-01-19 11:22:28 +030089 * See [CoroutineDispatcher] for the standard [context] implementations that are provided by `kotlinx.coroutines`.
Roman Elizarov44ba4b12017-01-25 11:37:54 +030090 * 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 Elizarov32d95322017-02-09 15:57:31 +030092 *
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 Elizarov3754f952017-01-18 20:47:54 +030099 */
Roman Elizarov32d95322017-02-09 15:57:31 +0300100public 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/**
111 * **Deprecated**: `defer` was renamed to `async`.
112 */
113@Deprecated(message = "`defer` was renamed to `async`", level = DeprecationLevel.WARNING,
114 replaceWith = ReplaceWith("async(context, block = block)"))
Roman Elizarovd528e3e2017-01-23 15:40:05 +0300115public fun <T> defer(context: CoroutineContext, block: suspend CoroutineScope.() -> T) : Deferred<T> =
Roman Elizarov32d95322017-02-09 15:57:31 +0300116 async(context, block = block)
Roman Elizarov3754f952017-01-18 20:47:54 +0300117
Roman Elizarov32d95322017-02-09 15:57:31 +0300118private open class DeferredCoroutine<T>(
119 context: CoroutineContext,
120 active: Boolean
121) : AbstractCoroutine<T>(context, active), Deferred<T> {
Roman Elizarovb7c46de2017-02-08 12:35:24 +0300122 override val isCompletedExceptionally: Boolean get() = getState() is CompletedExceptionally
123 override val isCancelled: Boolean get() = getState() is Cancelled
124
Roman Elizarov3754f952017-01-18 20:47:54 +0300125 @Suppress("UNCHECKED_CAST")
126 suspend override fun await(): T {
Roman Elizarov32d95322017-02-09 15:57:31 +0300127 // 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 Elizarov41c5c8b2017-01-25 13:37:15 +0300132 if (state is CompletedExceptionally) throw state.exception
133 return state as T
Roman Elizarov32d95322017-02-09 15:57:31 +0300134
Roman Elizarov41c5c8b2017-01-25 13:37:15 +0300135 }
Roman Elizarov32d95322017-02-09 15:57:31 +0300136 if (startInternal(state) >= 0) break // break unless needs to retry
Roman Elizarov41c5c8b2017-01-25 13:37:15 +0300137 }
Roman Elizarov32d95322017-02-09 15:57:31 +0300138 return awaitSuspend() // slow-path
Roman Elizarov3754f952017-01-18 20:47:54 +0300139 }
140
141 @Suppress("UNCHECKED_CAST")
Roman Elizarov32d95322017-02-09 15:57:31 +0300142 private suspend fun awaitSuspend(): T = suspendCancellableCoroutine { cont ->
Roman Elizarov3754f952017-01-18 20:47:54 +0300143 cont.unregisterOnCompletion(onCompletion {
144 val state = getState()
Roman Elizarov32d95322017-02-09 15:57:31 +0300145 check(state !is Incomplete)
Roman Elizarov3754f952017-01-18 20:47:54 +0300146 if (state is CompletedExceptionally)
147 cont.resumeWithException(state.exception)
148 else
149 cont.resume(state as T)
150 })
151 }
152
Roman Elizarovc5814542017-01-19 10:19:06 +0300153 @Suppress("UNCHECKED_CAST")
154 override fun getCompleted(): T {
155 val state = getState()
Roman Elizarov32d95322017-02-09 15:57:31 +0300156 check(state !is Incomplete) { "This deferred value has not completed yet" }
Roman Elizarovc5814542017-01-19 10:19:06 +0300157 if (state is CompletedExceptionally) throw state.exception
158 return state as T
Roman Elizarov3754f952017-01-18 20:47:54 +0300159 }
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300160
161 // for nicer debugging
Roman Elizarov32d95322017-02-09 15:57:31 +0300162 override fun toString(): String {
163 val state = getState()
164 val result = if (state is Incomplete) "" else "[$state]"
165 return "${javaClass.simpleName}{${describeState(state)}}$result@${Integer.toHexString(System.identityHashCode(this))}"
166 }
167}
168
169private class LazyDeferredCoroutine<T>(
170 context: CoroutineContext,
171 val block: suspend CoroutineScope.() -> T
172) : DeferredCoroutine<T>(context, active = false) {
173 override fun onStart() {
174 block.startCoroutine(this, this)
175 }
Roman Elizarov3754f952017-01-18 20:47:54 +0300176}