forked from Kotlin/kotlinx.coroutines
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuilders.kt
335 lines (310 loc) · 10.3 KB
/
Builders.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:JvmMultifileClass
@file:JvmName("FlowKt")
package kotlinx.coroutines.flow
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.channels.Channel.Factory.BUFFERED
import kotlinx.coroutines.flow.internal.*
import kotlin.coroutines.*
import kotlin.jvm.*
/**
* Creates a flow from the given suspendable [block].
*
* Example of usage:
* ```
* fun fibonacci(): Flow<Long> = flow {
* emit(1L)
* var f1 = 1L
* var f2 = 1L
* repeat(100) {
* var tmp = f1
* f1 = f2
* f2 += tmp
* emit(f1)
* }
* }
* ```
*
* `emit` should happen strictly in the dispatchers of the [block] in order to preserve the flow context.
* For example, the following code will result in an [IllegalStateException]:
* ```
* flow {
* emit(1) // Ok
* withContext(Dispatcher.IO) {
* emit(2) // Will fail with ISE
* }
* }
* ```
* If you want to switch the context of execution of a flow, use the [flowOn] operator.
*/
@ExperimentalCoroutinesApi
public fun <T> flow(@BuilderInference block: suspend FlowCollector<T>.() -> Unit): Flow<T> {
return object : Flow<T> {
override suspend fun collect(collector: FlowCollector<T>) {
SafeCollector(collector, coroutineContext).block()
}
}
}
/**
* An analogue of the [flow] builder that does not check the context of execution of the resulting flow.
* Used in our own operators where we trust the context of invocations.
*/
@PublishedApi
internal inline fun <T> unsafeFlow(@BuilderInference crossinline block: suspend FlowCollector<T>.() -> Unit): Flow<T> {
return object : Flow<T> {
override suspend fun collect(collector: FlowCollector<T>) {
collector.block()
}
}
}
/**
* Creates a flow that produces a single value from the given functional type.
*/
@FlowPreview
public fun <T> (() -> T).asFlow(): Flow<T> = unsafeFlow {
emit(invoke())
}
/**
* Creates a flow that produces a single value from the given functional type.
* Example of usage:
* ```
* suspend fun remoteCall(): R = ...
* suspend fun remoteCallFlow(): Flow<R> = ::remoteCall.asFlow()
* ```
*/
@FlowPreview
public fun <T> (suspend () -> T).asFlow(): Flow<T> = unsafeFlow {
emit(invoke())
}
/**
* Creates a flow that produces values from the given iterable.
*/
@ExperimentalCoroutinesApi
public fun <T> Iterable<T>.asFlow(): Flow<T> = unsafeFlow {
forEach { value ->
emit(value)
}
}
/**
* Creates a flow that produces values from the given iterable.
*/
@ExperimentalCoroutinesApi
public fun <T> Iterator<T>.asFlow(): Flow<T> = unsafeFlow {
forEach { value ->
emit(value)
}
}
/**
* Creates a flow that produces values from the given sequence.
*/
@ExperimentalCoroutinesApi
public fun <T> Sequence<T>.asFlow(): Flow<T> = unsafeFlow {
forEach { value ->
emit(value)
}
}
/**
* Creates a flow that produces values from the given array of elements.
*/
@ExperimentalCoroutinesApi
public fun <T> flowOf(vararg elements: T): Flow<T> = unsafeFlow {
for (element in elements) {
emit(element)
}
}
/**
* Creates flow that produces a given [value].
*/
@ExperimentalCoroutinesApi
public fun <T> flowOf(value: T): Flow<T> = unsafeFlow {
/*
* Implementation note: this is just an "optimized" overload of flowOf(vararg)
* which significantly reduce the footprint of widespread single-value flows.
*/
emit(value)
}
/**
* Returns an empty flow.
*/
@ExperimentalCoroutinesApi
public fun <T> emptyFlow(): Flow<T> = EmptyFlow
private object EmptyFlow : Flow<Nothing> {
override suspend fun collect(collector: FlowCollector<Nothing>) = Unit
}
/**
* Creates a flow that produces values from the given array.
*/
@ExperimentalCoroutinesApi
public fun <T> Array<T>.asFlow(): Flow<T> = unsafeFlow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given array.
*/
@ExperimentalCoroutinesApi
public fun IntArray.asFlow(): Flow<Int> = unsafeFlow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given array.
*/
@ExperimentalCoroutinesApi
public fun LongArray.asFlow(): Flow<Long> = unsafeFlow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given range.
*/
@ExperimentalCoroutinesApi
public fun IntRange.asFlow(): Flow<Int> = unsafeFlow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given range.
*/
@ExperimentalCoroutinesApi
public fun LongRange.asFlow(): Flow<Long> = flow {
forEach { value ->
emit(value)
}
}
/**
* @suppress
*/
@FlowPreview
@Deprecated(
message = "Use channelFlow instead",
level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith("channelFlow(block)")
)
public fun <T> flowViaChannel(
bufferSize: Int = BUFFERED,
@BuilderInference block: CoroutineScope.(channel: SendChannel<T>) -> Unit
): Flow<T> {
return channelFlow<T> {
block(channel)
}.buffer(bufferSize)
}
/**
* Creates an instance of the cold [Flow] with elements that are sent to a [SendChannel]
* that is provided to the builder's [block] of code via [ProducerScope]. It allows elements to be
* produced by the code that is running in a different context or running concurrently.
* The resulting flow is _cold_, which means that [block] is called on each call of a terminal operator
* on the resulting flow.
*
* This builder ensures thread-safety and context preservation, thus the provided [ProducerScope] can be used
* concurrently from different contexts.
* The resulting flow completes as soon as the code in the [block] and all its children complete.
* Use [awaitClose] as the last statement to keep it running.
* For more detailed example please refer to [callbackFlow] documentation.
*
* A channel with [default][Channel.BUFFERED] buffer size is used. Use [buffer] operator on the
* resulting flow to specify a value other than default and to control what happens when data is produced faster
* than it is consumed, that is to control backpressure behavior.
*
* Adjacent applications of [channelFlow], [flowOn], [buffer], [produceIn], and [broadcastIn] are
* always fused so that only one properly configured channel is used for execution.
*
* Examples of usage:
*
* ```
* fun <T> Flow<T>.merge(other: Flow<T>): Flow<T> = channelFlow {
* // collect from one coroutine and send it
* launch {
* collect { send(it) }
* }
* // collect and send from this coroutine, too, concurrently
* other.collect { send(it) }
* }
*
* fun <T> contextualFlow(): Flow<T> = channelFlow {
* // send from one coroutine
* launch(Dispatchers.IO) {
* send(computeIoValue())
* }
* // send from another coroutine, concurrently
* launch(Dispatchers.Default) {
* send(computeCpuValue())
* }
* }
* ```
*/
@ExperimentalCoroutinesApi
public fun <T> channelFlow(@BuilderInference block: suspend ProducerScope<T>.() -> Unit): Flow<T> =
ChannelFlowBuilder(block)
/**
* Creates an instance of the cold [Flow] with elements that are sent to a [SendChannel]
* that is provided to the builder's [block] of code via [ProducerScope]. It allows elements to be
* produced by the code that is running in a different context or running concurrently.
*
* The resulting flow is _cold_, which means that [block] is called on each call of a terminal operator
* on the resulting flow.
*
* This builder ensures thread-safety and context preservation, thus the provided [ProducerScope] can be used
* from any context, e.g. from the callback-based API.
* The resulting flow completes as soon as the code in the [block] and all its children complete.
* Use [awaitClose] as the last statement to keep it running.
* [awaitClose] argument is called when either flow consumer cancels flow collection
* or when callback-based API invokes [SendChannel.close] manually.
*
* A channel with [default][Channel.BUFFERED] buffer size is used. Use [buffer] operator on the
* resulting flow to specify a value other than default and to control what happens when data is produced faster
* than it is consumed, that is to control backpressure behavior.
*
* Adjacent applications of [callbackFlow], [flowOn], [buffer], [produceIn], and [broadcastIn] are
* always fused so that only one properly configured channel is used for execution.
*
* Example of usage:
*
* ```
* fun flowFrom(api: CallbackBasedApi): Flow<T> = callbackFlow {
* val callback = object : Callback { // implementation of some callback interface
* override fun onNextValue(value: T) {
* // Note: offer drops values when the buffer is full
* // Use either buffer(Channel.CONFLATED) or buffer(Channel.UNLIMITED) to avoid overfill
* // Also, offer will throw if the channel is canceled.
* // To avoid that, we wrap the call in runCatching.
* // See https://github.com/Kotlin/kotlinx.coroutines/issues/974
* runCatching {
* offer(value)
* }
* }
* override fun onApiError(cause: Throwable) {
* cancel(CancellationException("API Error", cause))
* }
* override fun onCompleted() = channel.close()
* }
* api.register(callback)
* // Suspend until either onCompleted or external cancellation are invoked
* await { api.unregister(callback) }
* }
* ```
*/
@Suppress("NOTHING_TO_INLINE")
@ExperimentalCoroutinesApi
public inline fun <T> callbackFlow(@BuilderInference noinline block: suspend ProducerScope<T>.() -> Unit): Flow<T> =
channelFlow(block)
// ChannelFlow implementation that is the first in the chain of flow operations and introduces (builds) a flow
private class ChannelFlowBuilder<T>(
private val block: suspend ProducerScope<T>.() -> Unit,
context: CoroutineContext = EmptyCoroutineContext,
capacity: Int = BUFFERED
) : ChannelFlow<T>(context, capacity) {
override fun create(context: CoroutineContext, capacity: Int): ChannelFlow<T> =
ChannelFlowBuilder(block, context, capacity)
override suspend fun collectTo(scope: ProducerScope<T>) =
block(scope)
override fun toString(): String =
"block[$block] -> ${super.toString()}"
}