Skip to content

Commit 709f6d7

Browse files
elizarovqwwdfsad
authored andcommitted
Improve flowViaChannel docs
* Detailed introductory paragraph * Explanation on the meaning of "cold flow" * Better self-contained example
1 parent 8695f97 commit 709f6d7

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

kotlinx-coroutines-core/common/src/flow/Builders.kt

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -183,19 +183,33 @@ public fun LongRange.asFlow(): Flow<Long> = flow {
183183
}
184184

185185
/**
186-
* Creates an instance of the cold [Flow] from a supplied [SendChannel].
186+
* Creates an instance of the cold [Flow] with elements that are sent to a [SendChannel]
187+
* that is provided to the builder's [block] of code. It allows elements to be
188+
* produced by the code that is running in a different context,
189+
* e.g. from a callback-based API.
190+
*
191+
* The resulting flow is _cold_, which means that [block] is called on each call of a terminal operator
192+
* on the resulting flow.
187193
*
188194
* To control backpressure, [bufferSize] is used and matches directly the `capacity` parameter of [Channel] factory.
189195
* The provided channel can later be used by any external service to communicate with flow and its buffer determines
190196
* backpressure buffer size or its behaviour (e.g. in case when [Channel.CONFLATED] was used).
191197
*
192198
* Example of usage:
199+
*
193200
* ```
194-
* fun flowFrom(api: CallbackBasedApi): Flow<Int> = flowViaChannel { channel ->
195-
* val adapter = FlowSinkAdapter(channel) // implementation of callback interface
196-
* api.register(adapter)
201+
* fun flowFrom(api: CallbackBasedApi): Flow<T> = flowViaChannel { channel ->
202+
* val callback = object : Callback { // implementation of some callback interface
203+
* override fun onNextValue(value: T) {
204+
* channel.offer(value) // Note: offer drops value when buffer is full
205+
* }
206+
* override fun onApiError(cause: Throwable) {
207+
* channel.cancel("API Error", CancellationException(cause))
208+
* }
209+
* }
210+
* api.register(callback)
197211
* channel.invokeOnClose {
198-
* api.unregister(adapter)
212+
* api.unregister(callback)
199213
* }
200214
* }
201215
* ```

0 commit comments

Comments
 (0)