blob: 10a15e2a938b7e1e6769dbb17befd5dd2674ba2d [file] [log] [blame]
Roman Elizarova5e653f2017-02-13 13:49:55 +03001/*
Aurimas Liutikas7b140462021-05-12 21:56:16 +00002 * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarova5e653f2017-02-13 13:49:55 +03003 */
4
Roman Elizarov0950dfa2018-07-13 10:33:25 +03005package kotlinx.coroutines.channels
6
7import kotlinx.coroutines.*
Roman Elizarov0950dfa2018-07-13 10:33:25 +03008import kotlin.coroutines.*
Roman Elizarova5e653f2017-02-13 13:49:55 +03009
10/**
Yanis Baturaa7afd462019-08-05 20:32:34 +070011 * Scope for the [produce][CoroutineScope.produce] coroutine builder.
Roman Elizarov27b8f452018-09-20 21:23:41 +030012 *
Yanis Baturaa7afd462019-08-05 20:32:34 +070013 * **Note: This is an experimental api.** Behavior of producers that work as children in a parent scope with respect
Roman Elizarov27b8f452018-09-20 21:23:41 +030014 * to cancellation and error handling may change in the future.
Roman Elizarova5e653f2017-02-13 13:49:55 +030015 */
Roman Elizarov27b8f452018-09-20 21:23:41 +030016@ExperimentalCoroutinesApi
Roman Elizarovf1d9a4e2017-04-05 10:53:14 +030017public interface ProducerScope<in E> : CoroutineScope, SendChannel<E> {
Roman Elizarova5e653f2017-02-13 13:49:55 +030018 /**
Yanis Baturaa7afd462019-08-05 20:32:34 +070019 * A reference to the channel this coroutine [sends][send] elements to.
Roman Elizarova5e653f2017-02-13 13:49:55 +030020 * It is provided for convenience, so that the code in the coroutine can refer
Yanis Baturaa7afd462019-08-05 20:32:34 +070021 * to the channel as `channel` as opposed to `this`.
Roman Elizarova5e653f2017-02-13 13:49:55 +030022 * All the [SendChannel] functions on this interface delegate to
Yanis Baturaa7afd462019-08-05 20:32:34 +070023 * the channel instance returned by this property.
Roman Elizarova5e653f2017-02-13 13:49:55 +030024 */
Vsevolod Tolstopyatov9cbad7d2020-03-27 17:43:45 +030025 public val channel: SendChannel<E>
Roman Elizarova5e653f2017-02-13 13:49:55 +030026}
27
28/**
Vsevolod Tolstopyatovb08d61c2019-05-28 00:37:46 +030029 * Suspends the current coroutine until the channel is either [closed][SendChannel.close] or [cancelled][ReceiveChannel.cancel]
Roman Elizarov8773a262020-10-12 19:09:48 +030030 * and invokes the given [block] before resuming the coroutine.
31 *
32 * This suspending function is cancellable.
33 * There is a **prompt cancellation guarantee**. If the job was cancelled while this function was
34 * suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details.
Vsevolod Tolstopyatovb08d61c2019-05-28 00:37:46 +030035 *
Yanis Baturaa7afd462019-08-05 20:32:34 +070036 * Note that when the producer channel is cancelled, this function resumes with a cancellation exception.
37 * Therefore, in case of cancellation, no code after the call to this function will be executed.
38 * That's why this function takes a lambda parameter.
Vsevolod Tolstopyatovb08d61c2019-05-28 00:37:46 +030039 *
40 * Example of usage:
41 * ```
42 * val callbackEventsStream = produce {
43 * val disposable = registerChannelInCallback(channel)
44 * awaitClose { disposable.dispose() }
45 * }
46 * ```
47 */
48@ExperimentalCoroutinesApi
Louis CADb5a84932019-07-03 11:31:12 +020049public suspend fun ProducerScope<*>.awaitClose(block: () -> Unit = {}) {
Yanis Baturaa7afd462019-08-05 20:32:34 +070050 check(kotlin.coroutines.coroutineContext[Job] === this) { "awaitClose() can only be invoked from the producer context" }
Vsevolod Tolstopyatovb08d61c2019-05-28 00:37:46 +030051 try {
52 suspendCancellableCoroutine<Unit> { cont ->
53 invokeOnClose {
54 cont.resume(Unit)
55 }
56 }
57 } finally {
58 block()
59 }
60}
61
62/**
Yanis Baturaa7afd462019-08-05 20:32:34 +070063 * Launches a new coroutine to produce a stream of values by sending them to a channel
Roman Elizarovb555d912017-08-17 21:01:33 +030064 * and returns a reference to the coroutine as a [ReceiveChannel]. This resulting
Roman Elizarovc0e19f82017-02-27 11:59:14 +030065 * object can be used to [receive][ReceiveChannel.receive] elements produced by this coroutine.
Roman Elizarova5e653f2017-02-13 13:49:55 +030066 *
Yanis Baturaa7afd462019-08-05 20:32:34 +070067 * The scope of the coroutine contains the [ProducerScope] interface, which implements
68 * both [CoroutineScope] and [SendChannel], so that the coroutine can invoke
Roman Elizarova5e653f2017-02-13 13:49:55 +030069 * [send][SendChannel.send] directly. The channel is [closed][SendChannel.close]
70 * when the coroutine completes.
Roman Elizarovb555d912017-08-17 21:01:33 +030071 * The running coroutine is cancelled when its receive channel is [cancelled][ReceiveChannel.cancel].
Roman Elizarova5e653f2017-02-13 13:49:55 +030072 *
Yanis Baturaa7afd462019-08-05 20:32:34 +070073 * The coroutine context is inherited from this [CoroutineScope]. Additional context elements can be specified with the [context] argument.
74 * If the context does not have any dispatcher or other [ContinuationInterceptor], then [Dispatchers.Default] is used.
75 * The parent job is inherited from the [CoroutineScope] as well, but it can also be overridden
Marek Langiewiczf86af232019-10-06 14:10:26 +020076 * with a corresponding [context] element.
Roman Elizarova5e653f2017-02-13 13:49:55 +030077 *
Yanis Baturaa7afd462019-08-05 20:32:34 +070078 * Any uncaught exception in this coroutine will close the channel with this exception as the cause and
79 * the resulting channel will become _failed_, so that any attempt to receive from it thereafter will throw an exception.
Roman Elizarova5e653f2017-02-13 13:49:55 +030080 *
Roman Elizarov5633f912018-09-23 19:08:36 +030081 * The kind of the resulting channel depends on the specified [capacity] parameter.
Yanis Baturaa7afd462019-08-05 20:32:34 +070082 * See the [Channel] interface documentation for details.
Roman Elizarov89f8ff72018-03-14 13:39:03 +030083 *
Yanis Baturaa7afd462019-08-05 20:32:34 +070084 * See [newCoroutineContext] for a description of debugging facilities available for newly created coroutines.
Roman Elizarovc0e19f82017-02-27 11:59:14 +030085 *
Roman Elizarov27b8f452018-09-20 21:23:41 +030086 * **Note: This is an experimental api.** Behaviour of producers that work as children in a parent scope with respect
87 * to cancellation and error handling may change in the future.
88 *
Roman Elizarovdc29b072018-09-11 18:42:03 +030089 * @param context additional to [CoroutineScope.coroutineContext] context of the coroutine.
Roman Elizarovc0d559b2017-09-28 14:27:05 +030090 * @param capacity capacity of the channel's buffer (no buffer by default).
91 * @param block the coroutine code.
Roman Elizarova5e653f2017-02-13 13:49:55 +030092 */
Roman Elizarov27b8f452018-09-20 21:23:41 +030093@ExperimentalCoroutinesApi
94public fun <E> CoroutineScope.produce(
95 context: CoroutineContext = EmptyCoroutineContext,
96 capacity: Int = 0,
Roman Elizarov0950dfa2018-07-13 10:33:25 +030097 @BuilderInference block: suspend ProducerScope<E>.() -> Unit
Roman Elizarov34c34642020-10-13 14:02:52 +030098): ReceiveChannel<E> =
99 produce(context, capacity, BufferOverflow.SUSPEND, CoroutineStart.DEFAULT, onCompletion = null, block = block)
Roman Elizarov27b8f452018-09-20 21:23:41 +0300100
101/**
Yanis Baturaa7afd462019-08-05 20:32:34 +0700102 * **This is an internal API and should not be used from general code.**
103 * The `onCompletion` parameter will be redesigned.
104 * If you have to use the `onCompletion` operator, please report to https://github.com/Kotlin/kotlinx.coroutines/issues/.
Vsevolod Tolstopyatovc81dc912019-05-31 13:16:19 +0300105 * As a temporary solution, [invokeOnCompletion][Job.invokeOnCompletion] can be used instead:
106 * ```
107 * fun <E> ReceiveChannel<E>.myOperator(): ReceiveChannel<E> = GlobalScope.produce(Dispatchers.Unconfined) {
108 * coroutineContext[Job]?.invokeOnCompletion { consumes() }
109 * }
110 * ```
111 * @suppress
Roman Elizarov27b8f452018-09-20 21:23:41 +0300112 */
113@InternalCoroutinesApi
Vsevolod Tolstopyatov79414ec2018-08-30 16:50:56 +0300114public fun <E> CoroutineScope.produce(
115 context: CoroutineContext = EmptyCoroutineContext,
Roman Elizarova5e653f2017-02-13 13:49:55 +0300116 capacity: Int = 0,
Vsevolod Tolstopyatov4a53d232020-03-03 15:33:40 +0300117 start: CoroutineStart = CoroutineStart.DEFAULT,
Roman Elizarov55a66ac2018-03-12 20:15:07 +0300118 onCompletion: CompletionHandler? = null,
Roman Elizarov0950dfa2018-07-13 10:33:25 +0300119 @BuilderInference block: suspend ProducerScope<E>.() -> Unit
Roman Elizarov34c34642020-10-13 14:02:52 +0300120): ReceiveChannel<E> =
121 produce(context, capacity, BufferOverflow.SUSPEND, start, onCompletion, block)
122
123// Internal version of produce that is maximally flexible, but is not exposed through public API (too many params)
124internal fun <E> CoroutineScope.produce(
125 context: CoroutineContext = EmptyCoroutineContext,
126 capacity: Int = 0,
127 onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND,
128 start: CoroutineStart = CoroutineStart.DEFAULT,
129 onCompletion: CompletionHandler? = null,
130 @BuilderInference block: suspend ProducerScope<E>.() -> Unit
Roman Elizarovb555d912017-08-17 21:01:33 +0300131): ReceiveChannel<E> {
Roman Elizarov34c34642020-10-13 14:02:52 +0300132 val channel = Channel<E>(capacity, onBufferOverflow)
Vsevolod Tolstopyatov79414ec2018-08-30 16:50:56 +0300133 val newContext = newCoroutineContext(context)
Roman Elizarove8f694e2017-11-28 10:12:00 +0300134 val coroutine = ProducerCoroutine(newContext, channel)
Roman Elizarov55a66ac2018-03-12 20:15:07 +0300135 if (onCompletion != null) coroutine.invokeOnCompletion(handler = onCompletion)
Vsevolod Tolstopyatov4a53d232020-03-03 15:33:40 +0300136 coroutine.start(start, coroutine, block)
Roman Elizarove8f694e2017-11-28 10:12:00 +0300137 return coroutine
Roman Elizarova5e653f2017-02-13 13:49:55 +0300138}
139
Vsevolod Tolstopyatov0342a0a2019-08-22 15:20:59 +0300140internal open class ProducerCoroutine<E>(
Roman Elizarov9faa61e2018-02-22 23:20:28 +0300141 parentContext: CoroutineContext, channel: Channel<E>
Vsevolod Tolstopyatovd92b0fa2018-10-08 19:41:18 +0300142) : ChannelCoroutine<E>(parentContext, channel, active = true), ProducerScope<E> {
Vsevolod Tolstopyatov79414ec2018-08-30 16:50:56 +0300143 override val isActive: Boolean
Vsevolod Tolstopyatovd92b0fa2018-10-08 19:41:18 +0300144 get() = super.isActive
Vsevolod Tolstopyatov79414ec2018-08-30 16:50:56 +0300145
Roman Elizarov6227c642019-03-19 13:22:19 +0300146 override fun onCompleted(value: Unit) {
147 _channel.close()
148 }
149
150 override fun onCancelled(cause: Throwable, handled: Boolean) {
Roman Elizarov6685fd02018-09-25 13:23:53 +0300151 val processed = _channel.close(cause)
Roman Elizarov6227c642019-03-19 13:22:19 +0300152 if (!processed && !handled) handleCoroutineException(context, cause)
Roman Elizarov9faa61e2018-02-22 23:20:28 +0300153 }
154}