Flow
An asynchronous data stream that sequentially emits values and completes normally or with an exception.
Intermediate operators on the flow such as map, filter, take, zip, etc are functions that are applied to the upstream flow or flows and return a downstream flow where further operators can be applied to. Intermediate operations do not execute any code in the flow and are not suspending functions themselves. They only set up a chain of operations for future execution and quickly return. This is known as a cold flow property.
Terminal operators on the flow are either suspending functions such as collect, single, reduce, toList, etc. or launchIn operator that starts collection of the flow in the given scope. They are applied to the upstream flow and trigger execution of all operations. Execution of the flow is also called collecting the flow and is always performed in a suspending manner without actual blocking. Terminal operators complete normally or exceptionally depending on successful or failed execution of all the flow operations in the upstream. The most basic terminal operator is collect, for example:
try {
flow.collect { value ->
println("Received $value")
}
} catch (e: Exception) {
println("The flow has thrown an exception: $e")
}
By default, flows are sequential and all flow operations are executed sequentially in the same coroutine, with an exception for a few operations specifically designed to introduce concurrency into flow execution such as buffer and flatMapMerge. See their documentation for details.
The Flow
interface does not carry information whether a flow is a cold stream that can be collected repeatedly and triggers execution of the same code every time it is collected, or if it is a hot stream that emits different values from the same running source on each collection. Usually flows represent cold streams, but there is a SharedFlow subtype that represents hot streams. In addition to that, any flow can be turned into a hot one by the stateIn and shareIn operators, or by converting the flow into a hot channel via the produceIn operator.
Flow builders
There are the following basic ways to create a flow:
flowOf(...) functions to create a flow from a fixed set of values.
asFlow() extension functions on various types to convert them into flows.
flow { ... } builder function to construct arbitrary flows from sequential calls to emit function.
channelFlow { ... } builder function to construct arbitrary flows from potentially concurrent calls to the send function.
MutableStateFlow and MutableSharedFlow define the corresponding constructor functions to create a hot flow that can be directly updated.
Flow constraints
All implementations of the Flow
interface must adhere to two key properties described in detail below:
Context preservation.
Exception transparency.
These properties ensure the ability to perform local reasoning about the code with flows and modularize the code in such a way that upstream flow emitters can be developed separately from downstream flow collectors. A user of a flow does not need to be aware of implementation details of the upstream flows it uses.
Context preservation
The flow has a context preservation property: it encapsulates its own execution context and never propagates or leaks it downstream, thus making reasoning about the execution context of particular transformations or terminal operations trivial.
There is only one way to change the context of a flow: the flowOn operator that changes the upstream context ("everything above the flowOn
operator"). For additional information refer to its documentation.
This reasoning can be demonstrated in practice:
val flowA = flowOf(1, 2, 3)
.map { it + 1 } // Will be executed in ctxA
.flowOn(ctxA) // Changes the upstream context: flowOf and map
// Now we have a context-preserving flow: it is executed somewhere but this information is encapsulated in the flow itself
val filtered = flowA // ctxA is encapsulated in flowA
.filter { it == 3 } // Pure operator without a context yet
withContext(Dispatchers.Main) {
// All non-encapsulated operators will be executed in Main: filter and single
val result = filtered.single()
myUi.text = result
}
From the implementation point of view, it means that all flow implementations should only emit from the same coroutine. This constraint is efficiently enforced by the default flow builder. The flow builder should be used if the flow implementation does not start any coroutines. Its implementation prevents most of the development mistakes:
val myFlow = flow {
// GlobalScope.launch { // is prohibited
// launch(Dispatchers.IO) { // is prohibited
// withContext(CoroutineName("myFlow")) { // is prohibited
emit(1) // OK
coroutineScope {
emit(2) // OK -- still the same coroutine
}
}
Use channelFlow if the collection and emission of a flow are to be separated into multiple coroutines. It encapsulates all the context preservation work and allows you to focus on your domain-specific problem, rather than invariant implementation details. It is possible to use any combination of coroutine builders from within channelFlow.
If you are looking for performance and are sure that no concurrent emits and context jumps will happen, the flow builder can be used alongside a coroutineScope or supervisorScope instead:
Scoped primitive should be used to provide a CoroutineScope.
Changing the context of emission is prohibited, no matter whether it is
withContext(ctx)
or a builder argument (e.g.launch(ctx)
).Collecting another flow from a separate context is allowed, but it has the same effect as applying the flowOn operator to that flow, which is more efficient.
Exception transparency
When emit
or emitAll
throws, the Flow implementations must immediately stop emitting new values and finish with an exception. For diagnostics or application-specific purposes, the exception may be different from the one thrown by the emit operation, suppressing the original exception as discussed below. If there is a need to emit values after the downstream failed, please use the catch operator.
The catch operator only catches upstream exceptions, but passes all downstream exceptions. Similarly, terminal operators like collect throw any unhandled exceptions that occur in their code or in upstream flows, for example:
flow { emitData() }
.map { computeOne(it) }
.catch { ... } // catches exceptions in emitData and computeOne
.map { computeTwo(it) }
.collect { process(it) } // throws exceptions from process and computeTwo
The same reasoning can be applied to the onCompletion operator that is a declarative replacement for the finally
block.
All exception-handling Flow operators follow the principle of exception suppression:
If the upstream flow throws an exception during its completion when the downstream exception has been thrown, the downstream exception becomes superseded and suppressed by the upstream exception, being a semantic equivalent of throwing from finally
block. However, this doesn't affect the operation of the exception-handling operators, which consider the downstream exception to be the root cause and behave as if the upstream didn't throw anything.
Failure to adhere to the exception transparency requirement can lead to strange behaviors which make it hard to reason about the code because an exception in the collect { ... }
could be somehow "caught" by an upstream flow, limiting the ability of local reasoning about the code.
Flow machinery enforces exception transparency at runtime and throws IllegalStateException on any attempt to emit a value, if an exception has been thrown on previous attempt.
Reactive streams
Flow is Reactive Streams compliant, you can safely interop it with reactive streams using Flow.asPublisher and Publisher.asFlow from kotlinx-coroutines-reactive
module.
Not stable for inheritance
The Flow
interface is not stable for inheritance in 3rd party libraries, as new methods might be added to this interface in the future, but is stable for use.
Use the flow { ... }
builder function to create an implementation, or extend AbstractFlow. These implementations ensure that the context preservation property is not violated, and prevent most of the developer mistakes related to concurrency, inconsistent flow dispatchers, and cancellation.
Inheritors
Functions
Returns a flow which checks cancellation status on each emission and throws the corresponding cancellation cause if flow collector was cancelled. Note that flow builder and all implementations of SharedFlow are cancellable by default.
Catches exceptions in the flow completion and calls a specified action with the caught exception. This operator is transparent to exceptions that occur in downstream flow and does not catch exceptions that are thrown to cancel the flow.
Terminal flow operator that collects the given flow with a provided action that takes the index of an element (zero-based) and the element. If any exception occurs during collect or in the provided flow, this exception is rethrown from this method.
Returns flow where all subsequent repetitions of the same value are filtered out.
Returns flow where all subsequent repetitions of the same value are filtered out, when compared with each other via the provided areEquivalent function.
Returns flow where all subsequent repetitions of the same key are filtered out, where key is extracted with keySelector function.
The terminal operator that returns the first element emitted by the flow and then cancels flow's collection. Throws NoSuchElementException if the flow was empty.
The terminal operator that returns the first element emitted by the flow matching the given predicate and then cancels flow's collection. Throws NoSuchElementException if the flow has not contained elements matching the predicate.
The terminal operator that returns the first element emitted by the flow and then cancels flow's collection. Returns null
if the flow was empty.
Returns a flow that switches to a new flow produced by transform function every time the original flow emits a value. When the original flow emits a new value, the previous flow produced by transform
block is cancelled.
Flattens the given flow of flows into a single flow in a sequential manner, without interleaving nested flows.
Flattens the given flow of flows into a single flow with a concurrency limit on the number of concurrently collected flows.
The terminal operator that returns the last element emitted by the flow or null
if the flow was empty.
Terminal flow operator that launches the collection of the given flow in the scope. It is a shorthand for scope.launch { flow.collect() }
.
Creates a produce coroutine that collects the given flow.
Retries collection of the given flow when an exception occurs in the upstream flow and the predicate returns true. The predicate also receives an attempt
number as parameter, starting from zero on the initial call. This operator is transparent to exceptions that occur in downstream flow and does not retry on exceptions that are thrown to cancel the flow.
Returns a flow that emits only the latest value emitted by the original flow during the given sampling period.
"java.time" adapter method for kotlinx.coroutines.flow.sample.
Converts a cold Flow into a hot SharedFlow that is started in the given coroutine scope, sharing emissions from a single running instance of the upstream flow with multiple downstream subscribers, and replaying a specified number of replay values to new subscribers. See the SharedFlow documentation for the general concepts of shared flows.
The terminal operator that awaits for one and only one value to be emitted. Throws NoSuchElementException for empty flow and IllegalArgumentException for flow that contains more than one element.
The terminal operator that awaits for one and only one value to be emitted. Returns the single value or null
, if the flow was empty or emitted more than one value.
Starts the upstream flow in a given scope, suspends until the first value is emitted, and returns a hot StateFlow of future emissions, sharing the most recently emitted value from this running instance of the upstream flow with multiple downstream subscribers. See the StateFlow documentation for the general concepts of state flows.
Returns a flow that will emit a TimeoutCancellationException if the upstream doesn't emit an item within the given time.
Collects given flow into a destination
Collects given flow into a destination
Collects given flow into a destination
Returns a flow that produces element by transform function every time the original flow emits a value. When the original flow emits a new value, the previous transform
block is cancelled, thus the name transformLatest
.
Returns a flow that wraps each element into IndexedValue, containing value and its index (starting from zero).