-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathBuilders.kt
235 lines (215 loc) · 5.79 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
/*
* 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.flow.internal.*
import kotlin.coroutines.*
import kotlin.jvm.*
/**
* Creates 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 flow purity.
* For example, the following code will produce [IllegalStateException]:
* ```
* flow {
* emit(1) // Ok
* withContext(Dispatcher.IO) {
* emit(2) // Will fail with ISE
* }
* }
* ```
* If you want to switch the context where this flow is executed use [flowOn] operator.
*/
@FlowPreview
public fun <T> flow(@BuilderInference block: suspend FlowCollector<in T>.() -> Unit): Flow<T> {
return object : Flow<T> {
override suspend fun collect(collector: FlowCollector<in T>) {
SafeCollector(collector, coroutineContext[ContinuationInterceptor]).block()
}
}
}
/**
* Analogue of [flow] builder that does not check a context of flow execution.
* Used in our own operators where we trust the context of the invocation.
*/
@FlowPreview
@PublishedApi
internal fun <T> unsafeFlow(@BuilderInference block: suspend FlowCollector<in T>.() -> Unit): Flow<T> {
return object : Flow<T> {
override suspend fun collect(collector: FlowCollector<in T>) {
collector.block()
}
}
}
/**
* Creates flow that produces single value from the given functional type.
*/
@FlowPreview
public fun <T> (() -> T).asFlow(): Flow<T> = unsafeFlow {
emit(invoke())
}
/**
* Creates flow that produces single value from the given functional type.
*/
@FlowPreview
public fun <T> (suspend () -> T).asFlow(): Flow<T> = unsafeFlow {
emit(invoke())
}
/**
* Creates flow that produces values from the given iterable.
*/
@FlowPreview
public fun <T> Iterable<T>.asFlow(): Flow<T> = unsafeFlow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given iterable.
*/
@FlowPreview
public fun <T> Iterator<T>.asFlow(): Flow<T> = unsafeFlow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given sequence.
*/
@FlowPreview
public fun <T> Sequence<T>.asFlow(): Flow<T> = unsafeFlow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given array of elements.
*/
@FlowPreview
public fun <T> flowOf(vararg elements: T): Flow<T> = unsafeFlow {
for (element in elements) {
emit(element)
}
}
/**
* Returns an empty flow.
*/
@FlowPreview
public fun <T> emptyFlow(): Flow<T> = EmptyFlow
private object EmptyFlow : Flow<Nothing> {
override suspend fun collect(collector: FlowCollector<in Nothing>) = Unit
}
/**
* Creates flow that produces values from the given array.
*/
@FlowPreview
public fun <T> Array<T>.asFlow(): Flow<T> = flow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given array.
*/
@FlowPreview
public fun IntArray.asFlow(): Flow<Int> = flow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given array.
*/
@FlowPreview
public fun LongArray.asFlow(): Flow<Long> = flow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given range.
*/
@FlowPreview
public fun IntRange.asFlow(): Flow<Int> = flow {
forEach { value ->
emit(value)
}
}
/**
* Creates flow that produces values from the given range.
*/
@FlowPreview
public fun LongRange.asFlow(): Flow<Long> = flow {
forEach { value ->
emit(value)
}
}
/**
* 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. It allows elements to be
* produced by the code that is running in a different context,
* e.g. from a callback-based API.
*
* The resulting flow is _cold_, which means that [block] is called on each call of a terminal operator
* on the resulting flow.
*
* To control backpressure, [bufferSize] is used and matches directly the `capacity` parameter of [Channel] factory.
* The provided channel can later be used by any external service to communicate with flow and its buffer determines
* backpressure buffer size or its behaviour (e.g. in case when [Channel.CONFLATED] was used).
*
* Example of usage:
*
* ```
* fun flowFrom(api: CallbackBasedApi): Flow<T> = flowViaChannel { channel ->
* val callback = object : Callback { // implementation of some callback interface
* override fun onNextValue(value: T) {
* channel.offer(value) // Note: offer drops value when buffer is full
* }
* override fun onApiError(cause: Throwable) {
* channel.cancel("API Error", CancellationException(cause))
* }
* }
* api.register(callback)
* channel.invokeOnClose {
* api.unregister(callback)
* }
* }
* ```
*/
@FlowPreview
public fun <T> flowViaChannel(
bufferSize: Int = 16,
@BuilderInference block: suspend (SendChannel<T>) -> Unit
): Flow<T> {
require(bufferSize >= 0) { "Buffer size should be positive, but was $bufferSize" }
return flow {
coroutineScope {
val channel = Channel<T>(bufferSize)
launch {
block(channel)
}
channel.consumeEach { value ->
emit(value)
}
}
}
}