1 /*
<lambda>null2 * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3 */
4
5 package kotlinx.coroutines.channels
6
7 import kotlinx.coroutines.*
8 import kotlin.coroutines.*
9 import kotlinx.coroutines.flow.*
10
11 /**
12 * Scope for the [produce][CoroutineScope.produce], [callbackFlow] and [channelFlow] builders.
13 */
14 public interface ProducerScope<in E> : CoroutineScope, SendChannel<E> {
15 /**
16 * A reference to the channel this coroutine [sends][send] elements to.
17 * It is provided for convenience, so that the code in the coroutine can refer
18 * to the channel as `channel` as opposed to `this`.
19 * All the [SendChannel] functions on this interface delegate to
20 * the channel instance returned by this property.
21 */
22 public val channel: SendChannel<E>
23 }
24
25 /**
26 * Suspends the current coroutine until the channel is either [closed][SendChannel.close] or [cancelled][ReceiveChannel.cancel]
27 * and invokes the given [block] before resuming the coroutine.
28 *
29 * This suspending function is cancellable.
30 * There is a **prompt cancellation guarantee**. If the job was cancelled while this function was
31 * suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details.
32 *
33 * Note that when the producer channel is cancelled, this function resumes with a cancellation exception.
34 * Therefore, in case of cancellation, no code after the call to this function will be executed.
35 * That's why this function takes a lambda parameter.
36 *
37 * Example of usage:
38 * ```
39 * val callbackEventsStream = produce {
40 * val disposable = registerChannelInCallback(channel)
41 * awaitClose { disposable.dispose() }
42 * }
43 * ```
44 */
<lambda>null45 public suspend fun ProducerScope<*>.awaitClose(block: () -> Unit = {}) {
<lambda>null46 check(kotlin.coroutines.coroutineContext[Job] === this) { "awaitClose() can only be invoked from the producer context" }
47 try {
contnull48 suspendCancellableCoroutine<Unit> { cont ->
49 invokeOnClose {
50 cont.resume(Unit)
51 }
52 }
53 } finally {
54 block()
55 }
56 }
57
58 /**
59 * Launches a new coroutine to produce a stream of values by sending them to a channel
60 * and returns a reference to the coroutine as a [ReceiveChannel]. This resulting
61 * object can be used to [receive][ReceiveChannel.receive] elements produced by this coroutine.
62 *
63 * The scope of the coroutine contains the [ProducerScope] interface, which implements
64 * both [CoroutineScope] and [SendChannel], so that the coroutine can invoke
65 * [send][SendChannel.send] directly. The channel is [closed][SendChannel.close]
66 * when the coroutine completes.
67 * The running coroutine is cancelled when its receive channel is [cancelled][ReceiveChannel.cancel].
68 *
69 * The coroutine context is inherited from this [CoroutineScope]. Additional context elements can be specified with the [context] argument.
70 * If the context does not have any dispatcher or other [ContinuationInterceptor], then [Dispatchers.Default] is used.
71 * The parent job is inherited from the [CoroutineScope] as well, but it can also be overridden
72 * with a corresponding [context] element.
73 *
74 * Any uncaught exception in this coroutine will close the channel with this exception as the cause and
75 * the resulting channel will become _failed_, so that any attempt to receive from it thereafter will throw an exception.
76 *
77 * The kind of the resulting channel depends on the specified [capacity] parameter.
78 * See the [Channel] interface documentation for details.
79 *
80 * See [newCoroutineContext] for a description of debugging facilities available for newly created coroutines.
81 *
82 * **Note: This is an experimental api.** Behaviour of producers that work as children in a parent scope with respect
83 * to cancellation and error handling may change in the future.
84 *
85 * @param context additional to [CoroutineScope.coroutineContext] context of the coroutine.
86 * @param capacity capacity of the channel's buffer (no buffer by default).
87 * @param block the coroutine code.
88 */
89 @ExperimentalCoroutinesApi
producenull90 public fun <E> CoroutineScope.produce(
91 context: CoroutineContext = EmptyCoroutineContext,
92 capacity: Int = 0,
93 @BuilderInference block: suspend ProducerScope<E>.() -> Unit
94 ): ReceiveChannel<E> =
95 produce(context, capacity, BufferOverflow.SUSPEND, CoroutineStart.DEFAULT, onCompletion = null, block = block)
96
97 /**
98 * **This is an internal API and should not be used from general code.**
99 * The `onCompletion` parameter will be redesigned.
100 * If you have to use the `onCompletion` operator, please report to https://github.com/Kotlin/kotlinx.coroutines/issues/.
101 * As a temporary solution, [invokeOnCompletion][Job.invokeOnCompletion] can be used instead:
102 * ```
103 * fun <E> ReceiveChannel<E>.myOperator(): ReceiveChannel<E> = GlobalScope.produce(Dispatchers.Unconfined) {
104 * coroutineContext[Job]?.invokeOnCompletion { consumes() }
105 * }
106 * ```
107 * @suppress
108 */
109 @InternalCoroutinesApi
110 public fun <E> CoroutineScope.produce(
111 context: CoroutineContext = EmptyCoroutineContext,
112 capacity: Int = 0,
113 start: CoroutineStart = CoroutineStart.DEFAULT,
114 onCompletion: CompletionHandler? = null,
115 @BuilderInference block: suspend ProducerScope<E>.() -> Unit
116 ): ReceiveChannel<E> =
117 produce(context, capacity, BufferOverflow.SUSPEND, start, onCompletion, block)
118
119 // Internal version of produce that is maximally flexible, but is not exposed through public API (too many params)
120 internal fun <E> CoroutineScope.produce(
121 context: CoroutineContext = EmptyCoroutineContext,
122 capacity: Int = 0,
123 onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND,
124 start: CoroutineStart = CoroutineStart.DEFAULT,
125 onCompletion: CompletionHandler? = null,
126 @BuilderInference block: suspend ProducerScope<E>.() -> Unit
127 ): ReceiveChannel<E> {
128 val channel = Channel<E>(capacity, onBufferOverflow)
129 val newContext = newCoroutineContext(context)
130 val coroutine = ProducerCoroutine(newContext, channel)
131 if (onCompletion != null) coroutine.invokeOnCompletion(handler = onCompletion)
132 coroutine.start(start, coroutine, block)
133 return coroutine
134 }
135
136 private class ProducerCoroutine<E>(
137 parentContext: CoroutineContext, channel: Channel<E>
138 ) : ChannelCoroutine<E>(parentContext, channel, true, active = true), ProducerScope<E> {
139 override val isActive: Boolean
140 get() = super.isActive
141
onCompletednull142 override fun onCompleted(value: Unit) {
143 _channel.close()
144 }
145
onCancellednull146 override fun onCancelled(cause: Throwable, handled: Boolean) {
147 val processed = _channel.close(cause)
148 if (!processed && !handled) handleCoroutineException(context, cause)
149 }
150 }
151