A suspending function asynchronously returns a single value, but how can we return multiple asynchronously computed values? This is where Kotlin Flows come in.

    Multiple values can be represented in Kotlin using collections. For example, we can have a function that returns a of three numbers and then print them all using forEach:

    This code outputs:

    1. 1
    2. 2
    3. 3

    Sequences

    If we are computing the numbers with some CPU-consuming blocking code (each computation taking 100ms), then we can represent the numbers using a Sequence:

    1. fun simple(): Sequence<Int> = sequence { // sequence builder
    2. for (i in 1..3) {
    3. Thread.sleep(100) // pretend we are computing it
    4. yield(i) // yield next value
    5. }
    6. }
    7. fun main() {
    8. simple().forEach { value -> println(value) }
    9. }

    You can get the full code from .

    This code outputs the same numbers, but it waits 100ms before printing each one.

    Suspending functions

    However, this computation blocks the main thread that is running the code. When these values are computed by asynchronous code we can mark the simple function with a suspend modifier, so that it can perform its work without blocking and return the result as a list:

    1. import kotlinx.coroutines.*
    2. //sampleStart
    3. suspend fun simple(): List<Int> {
    4. delay(1000) // pretend we are doing something asynchronous here
    5. return listOf(1, 2, 3)
    6. }
    7. fun main() = runBlocking<Unit> {
    8. simple().forEach { value -> println(value) }
    9. }
    10. //sampleEnd

    You can get the full code from .

    This code prints the numbers after waiting for a second.

    Flows

    Using the List<Int> result type, means we can only return all the values at once. To represent the stream of values that are being asynchronously computed, we can use a type just like we would use the Sequence<Int> type for synchronously computed values:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun simple(): Flow<Int> = flow { // flow builder
    5. for (i in 1..3) {
    6. delay(100) // pretend we are doing something useful here
    7. emit(i) // emit next value
    8. }
    9. }
    10. fun main() = runBlocking<Unit> {
    11. // Launch a concurrent coroutine to check if the main thread is blocked
    12. launch {
    13. for (k in 1..3) {
    14. println("I'm not blocked $k")
    15. delay(100)
    16. }
    17. }
    18. // Collect the flow
    19. simple().collect { value -> println(value) }
    20. }
    21. //sampleEnd

    You can get the full code from here.

    This code waits 100ms before printing each number without blocking the main thread. This is verified by printing “I’m not blocked” every 100ms from a separate coroutine that is running in the main thread:

    1. I'm not blocked 1
    2. 1
    3. I'm not blocked 2
    4. 2
    5. I'm not blocked 3
    6. 3

    Notice the following differences in the code with the from the earlier examples:

    • A builder function for Flow type is called .
    • Code inside the flow { ... } builder block can suspend.
    • The simple function is no longer marked with suspend modifier.
    • Values are emitted from the flow using emit function.
    • Values are collected from the flow using function.

    We can replace delay with Thread.sleep in the body of simple‘s flow { ... } and see that the main thread is blocked in this case.

    Flows are cold

    Flows are cold streams similar to sequences — the code inside a flow builder does not run until the flow is collected. This becomes clear in the following example:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun simple(): Flow<Int> = flow {
    5. println("Flow started")
    6. for (i in 1..3) {
    7. delay(100)
    8. emit(i)
    9. }
    10. }
    11. fun main() = runBlocking<Unit> {
    12. println("Calling simple function...")
    13. val flow = simple()
    14. println("Calling collect...")
    15. flow.collect { value -> println(value) }
    16. println("Calling collect again...")
    17. flow.collect { value -> println(value) }
    18. }
    19. //sampleEnd

    You can get the full code from .

    Which prints:

    1. Calling simple function...
    2. Calling collect...
    3. Flow started
    4. 1
    5. 2
    6. 3
    7. Calling collect again...
    8. Flow started
    9. 1
    10. 2
    11. 3

    This is a key reason the simple function (which returns a flow) is not marked with suspend modifier. By itself, simple() call returns quickly and does not wait for anything. The flow starts every time it is collected, that is why we see “Flow started” when we call collect again.

    Flow cancellation basics

    Flow adheres to the general cooperative cancellation of coroutines. As usual, flow collection can be cancelled when the flow is suspended in a cancellable suspending function (like ). The following example shows how the flow gets cancelled on a timeout when running in a withTimeoutOrNull block and stops executing its code:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun simple(): Flow<Int> = flow {
    5. for (i in 1..3) {
    6. delay(100)
    7. println("Emitting $i")
    8. emit(i)
    9. }
    10. }
    11. fun main() = runBlocking<Unit> {
    12. withTimeoutOrNull(250) { // Timeout after 250ms
    13. simple().collect { value -> println(value) }
    14. }
    15. println("Done")
    16. }
    17. //sampleEnd

    You can get the full code from .

    Notice how only two numbers get emitted by the flow in the simple function, producing the following output:

    1. Emitting 1
    2. 1
    3. Emitting 2
    4. 2
    5. Done

    See Flow cancellation checks section for more details.

    Flow builders

    The flow { ... } builder from the previous examples is the most basic one. There are other builders for easier declaration of flows:

    • flowOf builder that defines a flow emitting a fixed set of values.
    • Various collections and sequences can be converted to flows using .asFlow() extension functions.

    So, the example that prints the numbers from 1 to 3 from a flow can be written as:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun main() = runBlocking<Unit> {
    4. //sampleStart
    5. // Convert an integer range to a flow
    6. (1..3).asFlow().collect { value -> println(value) }
    7. //sampleEnd
    8. }

    You can get the full code from .

    Intermediate flow operators

    Flows can be transformed with operators, just as you would with collections and sequences. Intermediate operators are applied to an upstream flow and return a downstream flow. These operators are cold, just like flows are. A call to such an operator is not a suspending function itself. It works quickly, returning the definition of a new transformed flow.

    The basic operators have familiar names like and filter. The important difference to sequences is that blocks of code inside these operators can call suspending functions.

    For example, a flow of incoming requests can be mapped to the results with the operator, even when performing a request is a long-running operation that is implemented by a suspending function:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. suspend fun performRequest(request: Int): String {
    5. delay(1000) // imitate long-running asynchronous work
    6. return "response $request"
    7. }
    8. fun main() = runBlocking<Unit> {
    9. (1..3).asFlow() // a flow of requests
    10. .map { request -> performRequest(request) }
    11. .collect { response -> println(response) }
    12. }
    13. //sampleEnd

    You can get the full code from here.

    It produces the following three lines, each line appearing after each second:

    1. response 1
    2. response 2
    3. response 3

    Transform operator

    Among the flow transformation operators, the most general one is called transform. It can be used to imitate simple transformations like and filter, as well as implement more complex transformations. Using the transform operator, we can arbitrary values an arbitrary number of times.

    For example, using transform we can emit a string before performing a long-running asynchronous request and follow it with a response:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. suspend fun performRequest(request: Int): String {
    4. delay(1000) // imitate long-running asynchronous work
    5. return "response $request"
    6. }
    7. fun main() = runBlocking<Unit> {
    8. //sampleStart
    9. (1..3).asFlow() // a flow of requests
    10. .transform { request ->
    11. emit("Making request $request")
    12. emit(performRequest(request))
    13. }
    14. .collect { response -> println(response) }
    15. //sampleEnd
    16. }

    You can get the full code from here.

    The output of this code is:

    1. Making request 1
    2. response 1
    3. Making request 2
    4. response 2
    5. Making request 3
    6. response 3

    Size-limiting operators

    Size-limiting intermediate operators like take cancel the execution of the flow when the corresponding limit is reached. Cancellation in coroutines is always performed by throwing an exception, so that all the resource-management functions (like try { ... } finally { ... } blocks) operate normally in case of cancellation:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun numbers(): Flow<Int> = flow {
    5. try {
    6. emit(1)
    7. emit(2)
    8. println("This line will not execute")
    9. emit(3)
    10. } finally {
    11. println("Finally in numbers")
    12. }
    13. }
    14. fun main() = runBlocking<Unit> {
    15. numbers()
    16. .take(2) // take only the first two
    17. .collect { value -> println(value) }
    18. }
    19. //sampleEnd

    You can get the full code from .

    The output of this code clearly shows that the execution of the flow { ... } body in the numbers() function stopped after emitting the second number:

    1. 1
    2. 2
    3. Finally in numbers

    Terminal flow operators

    Terminal operators on flows are suspending functions that start a collection of the flow. The operator is the most basic one, but there are other terminal operators, which can make it easier:

    • Conversion to various collections like toList and .
    • Operators to get the first value and to ensure that a flow emits a value.
    • Reducing a flow to a value with reduce and .

    For example:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun main() = runBlocking<Unit> {
    4. //sampleStart
    5. val sum = (1..5).asFlow()
    6. .map { it * it } // squares of numbers from 1 to 5
    7. .reduce { a, b -> a + b } // sum them (terminal operator)
    8. println(sum)
    9. //sampleEnd

    You can get the full code from here.

    Prints a single number:

    1. 55

    Each individual collection of a flow is performed sequentially unless special operators that operate on multiple flows are used. The collection works directly in the coroutine that calls a terminal operator. No new coroutines are launched by default. Each emitted value is processed by all the intermediate operators from upstream to downstream and is then delivered to the terminal operator after.

    See the following example that filters the even integers and maps them to strings:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun main() = runBlocking<Unit> {
    4. //sampleStart
    5. (1..5).asFlow()
    6. .filter {
    7. println("Filter $it")
    8. it % 2 == 0
    9. }
    10. .map {
    11. println("Map $it")
    12. "string $it"
    13. }.collect {
    14. println("Collect $it")
    15. }
    16. //sampleEnd
    17. }

    You can get the full code from .

    Producing:

    1. Filter 1
    2. Filter 2
    3. Map 2
    4. Collect string 2
    5. Filter 3
    6. Filter 4
    7. Map 4
    8. Collect string 4
    9. Filter 5

    Flow context

    Collection of a flow always happens in the context of the calling coroutine. For example, if there is a simple flow, then the following code runs in the context specified by the author of this code, regardless of the implementation details of the simple flow:

    1. withContext(context) {
    2. simple().collect { value ->
    3. println(value) // run in the specified context
    4. }
    5. }

    This property of a flow is called context preservation.

    So, by default, code in the flow { ... } builder runs in the context that is provided by a collector of the corresponding flow. For example, consider the implementation of a simple function that prints the thread it is called on and emits three numbers:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
    4. //sampleStart
    5. fun simple(): Flow<Int> = flow {
    6. log("Started simple flow")
    7. for (i in 1..3) {
    8. emit(i)
    9. }
    10. }
    11. fun main() = runBlocking<Unit> {
    12. simple().collect { value -> log("Collected $value") }
    13. }
    14. //sampleEnd

    You can get the full code from .

    1. [main @coroutine#1] Started simple flow
    2. [main @coroutine#1] Collected 1
    3. [main @coroutine#1] Collected 2
    4. [main @coroutine#1] Collected 3

    Since simple().collect is called from the main thread, the body of simple‘s flow is also called in the main thread. This is the perfect default for fast-running or asynchronous code that does not care about the execution context and does not block the caller.

    Wrong emission withContext

    However, the long-running CPU-consuming code might need to be executed in the context of and UI-updating code might need to be executed in the context of Dispatchers.Main. Usually, is used to change the context in the code using Kotlin coroutines, but code in the flow { ... } builder has to honor the context preservation property and is not allowed to emit from a different context.

    Try running the following code:

    This code produces the following exception:

    1. Exception in thread "main" java.lang.IllegalStateException: Flow invariant is violated:
    2. Flow was collected in [CoroutineId(1), "coroutine#1":BlockingCoroutine{Active}@5511c7f8, BlockingEventLoop@2eac3323],
    3. but emission happened in [CoroutineId(1), "coroutine#1":DispatchedCoroutine{Active}@2dae0000, Dispatchers.Default].
    4. Please refer to 'flow' documentation or use 'flowOn' instead

    flowOn operator

    The exception refers to the flowOn function that shall be used to change the context of the flow emission. The correct way to change the context of a flow is shown in the example below, which also prints the names of the corresponding threads to show how it all works:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
    4. //sampleStart
    5. fun simple(): Flow<Int> = flow {
    6. for (i in 1..3) {
    7. Thread.sleep(100) // pretend we are computing it in CPU-consuming way
    8. log("Emitting $i")
    9. emit(i) // emit next value
    10. }
    11. }.flowOn(Dispatchers.Default) // RIGHT way to change context for CPU-consuming code in flow builder
    12. fun main() = runBlocking<Unit> {
    13. simple().collect { value ->
    14. log("Collected $value")
    15. }
    16. }
    17. //sampleEnd

    You can get the full code from .

    Notice how flow { ... } works in the background thread, while collection happens in the main thread:

    Another thing to observe here is that the flowOn operator has changed the default sequential nature of the flow. Now collection happens in one coroutine (“coroutine#1”) and emission happens in another coroutine (“coroutine#2”) that is running in another thread concurrently with the collecting coroutine. The operator creates another coroutine for an upstream flow when it has to change the CoroutineDispatcher in its context.

    Buffering

    Running different parts of a flow in different coroutines can be helpful from the standpoint of the overall time it takes to collect the flow, especially when long-running asynchronous operations are involved. For example, consider a case when the emission by a simple flow is slow, taking 100 ms to produce an element; and collector is also slow, taking 300 ms to process an element. Let’s see how long it takes to collect such a flow with three numbers:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. import kotlin.system.*
    4. //sampleStart
    5. fun simple(): Flow<Int> = flow {
    6. for (i in 1..3) {
    7. delay(100) // pretend we are asynchronously waiting 100 ms
    8. emit(i) // emit next value
    9. }
    10. }
    11. fun main() = runBlocking<Unit> {
    12. val time = measureTimeMillis {
    13. simple().collect { value ->
    14. delay(300) // pretend we are processing it for 300 ms
    15. println(value)
    16. }
    17. }
    18. println("Collected in $time ms")
    19. }
    20. //sampleEnd

    You can get the full code from here.

    It produces something like this, with the whole collection taking around 1200 ms (three numbers, 400 ms for each):

    1. 1
    2. 2
    3. 3
    4. Collected in 1220 ms

    We can use a operator on a flow to run emitting code of the simple flow concurrently with collecting code, as opposed to running them sequentially:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. import kotlin.system.*
    4. fun simple(): Flow<Int> = flow {
    5. for (i in 1..3) {
    6. delay(100) // pretend we are asynchronously waiting 100 ms
    7. emit(i) // emit next value
    8. }
    9. }
    10. fun main() = runBlocking<Unit> {
    11. //sampleStart
    12. val time = measureTimeMillis {
    13. simple()
    14. .buffer() // buffer emissions, don't wait
    15. .collect { value ->
    16. delay(300) // pretend we are processing it for 300 ms
    17. println(value)
    18. }
    19. }
    20. println("Collected in $time ms")
    21. //sampleEnd
    22. }

    You can get the full code from here.

    It produces the same numbers just faster, as we have effectively created a processing pipeline, having to only wait 100 ms for the first number and then spending only 300 ms to process each number. This way it takes around 1000 ms to run:

    1. 1
    2. 2
    3. 3
    4. Collected in 1071 ms

    Note that the operator uses the same buffering mechanism when it has to change a CoroutineDispatcher, but here we explicitly request buffering without changing the execution context.

    Conflation

    When a flow represents partial results of the operation or operation status updates, it may not be necessary to process each value, but instead, only most recent ones. In this case, the conflate operator can be used to skip intermediate values when a collector is too slow to process them. Building on the previous example:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. import kotlin.system.*
    4. fun simple(): Flow<Int> = flow {
    5. for (i in 1..3) {
    6. delay(100) // pretend we are asynchronously waiting 100 ms
    7. emit(i) // emit next value
    8. }
    9. }
    10. fun main() = runBlocking<Unit> {
    11. //sampleStart
    12. val time = measureTimeMillis {
    13. simple()
    14. .conflate() // conflate emissions, don't process each one
    15. .collect { value ->
    16. delay(300) // pretend we are processing it for 300 ms
    17. println(value)
    18. }
    19. }
    20. println("Collected in $time ms")
    21. //sampleEnd
    22. }

    You can get the full code from .

    We see that while the first number was still being processed the second, and third were already produced, so the second one was conflated and only the most recent (the third one) was delivered to the collector:

    1. 1
    2. 3
    3. Collected in 758 ms

    Processing the latest value

    Conflation is one way to speed up processing when both the emitter and collector are slow. It does it by dropping emitted values. The other way is to cancel a slow collector and restart it every time a new value is emitted. There is a family of xxxLatest operators that perform the same essential logic of a xxx operator, but cancel the code in their block on a new value. Let’s try changing to collectLatest in the previous example:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. import kotlin.system.*
    4. fun simple(): Flow<Int> = flow {
    5. for (i in 1..3) {
    6. delay(100) // pretend we are asynchronously waiting 100 ms
    7. emit(i) // emit next value
    8. }
    9. }
    10. fun main() = runBlocking<Unit> {
    11. //sampleStart
    12. val time = measureTimeMillis {
    13. simple()
    14. .collectLatest { value -> // cancel & restart on the latest value
    15. println("Collecting $value")
    16. delay(300) // pretend we are processing it for 300 ms
    17. println("Done $value")
    18. }
    19. }
    20. println("Collected in $time ms")
    21. //sampleEnd
    22. }

    You can get the full code from .

    Since the body of collectLatest takes 300 ms, but new values are emitted every 100 ms, we see that the block is run on every value, but completes only for the last value:

    1. Collecting 1
    2. Collecting 2
    3. Collecting 3
    4. Done 3
    5. Collected in 741 ms

    Composing multiple flows

    There are lots of ways to compose multiple flows.

    Zip

    Just like the extension function in the Kotlin standard library, flows have a zip operator that combines the corresponding values of two flows:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun main() = runBlocking<Unit> {
    4. //sampleStart
    5. val nums = (1..3).asFlow() // numbers 1..3
    6. val strs = flowOf("one", "two", "three") // strings
    7. nums.zip(strs) { a, b -> "$a -> $b" } // compose a single string
    8. .collect { println(it) } // collect and print
    9. //sampleEnd
    10. }

    You can get the full code from .

    This example prints:

    1. 1 -> one
    2. 2 -> two
    3. 3 -> three

    Combine

    When flow represents the most recent value of a variable or operation (see also the related section on ), it might be needed to perform a computation that depends on the most recent values of the corresponding flows and to recompute it whenever any of the upstream flows emit a value. The corresponding family of operators is called combine.

    For example, if the numbers in the previous example update every 300ms, but strings update every 400 ms, then zipping them using the operator will still produce the same result, albeit results that are printed every 400 ms:

    We use a onEach intermediate operator in this example to delay each element and make the code that emits sample flows more declarative and shorter.

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun main() = runBlocking<Unit> {
    4. //sampleStart
    5. val nums = (1..3).asFlow().onEach { delay(300) } // numbers 1..3 every 300 ms
    6. val strs = flowOf("one", "two", "three").onEach { delay(400) } // strings every 400 ms
    7. val startTime = System.currentTimeMillis() // remember the start time
    8. nums.zip(strs) { a, b -> "$a -> $b" } // compose a single string with "zip"
    9. .collect { value -> // collect and print
    10. println("$value at ${System.currentTimeMillis() - startTime} ms from start")
    11. }
    12. //sampleEnd
    13. }

    You can get the full code from .

    However, when using a combine operator here instead of a :

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun main() = runBlocking<Unit> {
    4. //sampleStart
    5. val nums = (1..3).asFlow().onEach { delay(300) } // numbers 1..3 every 300 ms
    6. val strs = flowOf("one", "two", "three").onEach { delay(400) } // strings every 400 ms
    7. val startTime = System.currentTimeMillis() // remember the start time
    8. nums.combine(strs) { a, b -> "$a -> $b" } // compose a single string with "combine"
    9. .collect { value -> // collect and print
    10. println("$value at ${System.currentTimeMillis() - startTime} ms from start")
    11. }
    12. //sampleEnd
    13. }

    You can get the full code from here.

    We get quite a different output, where a line is printed at each emission from either nums or strs flows:

    1. 1 -> one at 452 ms from start
    2. 2 -> one at 651 ms from start
    3. 2 -> two at 854 ms from start
    4. 3 -> two at 952 ms from start
    5. 3 -> three at 1256 ms from start

    Flattening flows

    Flows represent asynchronously received sequences of values, so it is quite easy to get in a situation where each value triggers a request for another sequence of values. For example, we can have the following function that returns a flow of two strings 500 ms apart:

    1. fun requestFlow(i: Int): Flow<String> = flow {
    2. emit("$i: First")
    3. delay(500) // wait 500 ms
    4. emit("$i: Second")
    5. }

    Now if we have a flow of three integers and call requestFlow for each of them like this:

    1. (1..3).asFlow().map { requestFlow(it) }

    Then we end up with a flow of flows (Flow<Flow<String>>) that needs to be flattened into a single flow for further processing. Collections and sequences have flatten and operators for this. However, due to the asynchronous nature of flows they call for different modes of flattening, as such, there is a family of flattening operators on flows.

    flatMapConcat

    Concatenating mode is implemented by and flattenConcat operators. They are the most direct analogues of the corresponding sequence operators. They wait for the inner flow to complete before starting to collect the next one as the following example shows:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun requestFlow(i: Int): Flow<String> = flow {
    4. emit("$i: First")
    5. delay(500) // wait 500 ms
    6. emit("$i: Second")
    7. }
    8. fun main() = runBlocking<Unit> {
    9. //sampleStart
    10. val startTime = System.currentTimeMillis() // remember the start time
    11. (1..3).asFlow().onEach { delay(100) } // a number every 100 ms
    12. .flatMapConcat { requestFlow(it) }
    13. .collect { value -> // collect and print
    14. println("$value at ${System.currentTimeMillis() - startTime} ms from start")
    15. }
    16. //sampleEnd
    17. }

    You can get the full code from .

    The sequential nature of flatMapConcat is clearly seen in the output:

    1. 1: First at 121 ms from start
    2. 1: Second at 622 ms from start
    3. 2: First at 727 ms from start
    4. 2: Second at 1227 ms from start
    5. 3: First at 1328 ms from start
    6. 3: Second at 1829 ms from start

    flatMapMerge

    Another flattening mode is to concurrently collect all the incoming flows and merge their values into a single flow so that values are emitted as soon as possible. It is implemented by flatMapMerge and operators. They both accept an optional concurrency parameter that limits the number of concurrent flows that are collected at the same time (it is equal to DEFAULT_CONCURRENCY by default).

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun requestFlow(i: Int): Flow<String> = flow {
    4. emit("$i: First")
    5. delay(500) // wait 500 ms
    6. emit("$i: Second")
    7. }
    8. fun main() = runBlocking<Unit> {
    9. //sampleStart
    10. val startTime = System.currentTimeMillis() // remember the start time
    11. (1..3).asFlow().onEach { delay(100) } // a number every 100 ms
    12. .flatMapMerge { requestFlow(it) }
    13. .collect { value -> // collect and print
    14. println("$value at ${System.currentTimeMillis() - startTime} ms from start")
    15. }
    16. //sampleEnd
    17. }

    You can get the full code from .

    The concurrent nature of flatMapMerge is obvious:

    1. 2: First at 231 ms from start
    2. 3: First at 333 ms from start
    3. 1: Second at 639 ms from start
    4. 2: Second at 732 ms from start
    5. 3: Second at 833 ms from start

    Note that the calls its block of code ({ requestFlow(it) } in this example) sequentially, but collects the resulting flows concurrently, it is the equivalent of performing a sequential map { requestFlow(it) } first and then calling flattenMerge on the result.

    flatMapLatest

    In a similar way to the collectLatest operator, that was shown in section, there is the corresponding “Latest” flattening mode where a collection of the previous flow is cancelled as soon as new flow is emitted. It is implemented by the flatMapLatest operator.

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun requestFlow(i: Int): Flow<String> = flow {
    4. emit("$i: First")
    5. delay(500) // wait 500 ms
    6. emit("$i: Second")
    7. }
    8. fun main() = runBlocking<Unit> {
    9. //sampleStart
    10. val startTime = System.currentTimeMillis() // remember the start time
    11. (1..3).asFlow().onEach { delay(100) } // a number every 100 ms
    12. .flatMapLatest { requestFlow(it) }
    13. .collect { value -> // collect and print
    14. println("$value at ${System.currentTimeMillis() - startTime} ms from start")
    15. }
    16. //sampleEnd
    17. }

    The output here in this example is a good demonstration of how works:

    1. 1: First at 142 ms from start
    2. 2: First at 322 ms from start
    3. 3: First at 425 ms from start
    4. 3: Second at 931 ms from start

    Note that flatMapLatest cancels all the code in its block ({ requestFlow(it) } in this example) on a new value. It makes no difference in this particular example, because the call to requestFlow itself is fast, not-suspending, and cannot be cancelled. However, it would show up if we were to use suspending functions like delay in there.

    Flow exceptions

    Flow collection can complete with an exception when an emitter or code inside the operators throw an exception. There are several ways to handle these exceptions.

    Collector try and catch

    A collector can use Kotlin’s block to handle exceptions:

    You can get the full code from here.

    1. Emitting 1
    2. 1
    3. Emitting 2
    4. 2
    5. Caught java.lang.IllegalStateException: Collected 2

    Everything is caught

    The previous example actually catches any exception happening in the emitter or in any intermediate or terminal operators. For example, let’s change the code so that emitted values are mapped to strings, but the corresponding code produces an exception:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun simple(): Flow<String> =
    5. flow {
    6. for (i in 1..3) {
    7. emit(i) // emit next value
    8. }
    9. }
    10. .map { value ->
    11. check(value <= 1) { "Crashed on $value" }
    12. "string $value"
    13. }
    14. fun main() = runBlocking<Unit> {
    15. try {
    16. simple().collect { value -> println(value) }
    17. } catch (e: Throwable) {
    18. println("Caught $e")
    19. }
    20. }
    21. //sampleEnd

    You can get the full code from .

    This exception is still caught and collection is stopped:

    1. Emitting 1
    2. string 1
    3. Emitting 2
    4. Caught java.lang.IllegalStateException: Crashed on 2

    But how can code of the emitter encapsulate its exception handling behavior?

    Flows must be transparent to exceptions and it is a violation of the exception transparency to emit values in the flow { ... } builder from inside of a try/catch block. This guarantees that a collector throwing an exception can always catch it using try/catch as in the previous example.

    The emitter can use a operator that preserves this exception transparency and allows encapsulation of its exception handling. The body of the catch operator can analyze an exception and react to it in different ways depending on which exception was caught:

    • Exceptions can be rethrown using throw.
    • Exceptions can be turned into emission of values using emit from the body of .
    • Exceptions can be ignored, logged, or processed by some other code.

    For example, let us emit the text on catching an exception:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun simple(): Flow<String> =
    4. flow {
    5. for (i in 1..3) {
    6. println("Emitting $i")
    7. emit(i) // emit next value
    8. }
    9. }
    10. .map { value ->
    11. check(value <= 1) { "Crashed on $value" }
    12. "string $value"
    13. }
    14. fun main() = runBlocking<Unit> {
    15. //sampleStart
    16. simple()
    17. .catch { e -> emit("Caught $e") } // emit on exception
    18. .collect { value -> println(value) }
    19. //sampleEnd
    20. }

    You can get the full code from here.

    The output of the example is the same, even though we do not have try/catch around the code anymore.

    Transparent catch

    The catch intermediate operator, honoring exception transparency, catches only upstream exceptions (that is an exception from all the operators above catch, but not below it). If the block in collect { ... } (placed below catch) throws an exception then it escapes:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun simple(): Flow<Int> = flow {
    5. for (i in 1..3) {
    6. println("Emitting $i")
    7. emit(i)
    8. }
    9. }
    10. fun main() = runBlocking<Unit> {
    11. simple()
    12. .catch { e -> println("Caught $e") } // does not catch downstream exceptions
    13. .collect { value ->
    14. check(value <= 1) { "Collected $value" }
    15. println(value)
    16. }
    17. }
    18. //sampleEnd

    You can get the full code from .

    A “Caught …” message is not printed despite there being a catch operator:

    1. Emitting 1
    2. 1
    3. Emitting 2
    4. Exception in thread "main" java.lang.IllegalStateException: Collected 2
    5. at ...

    Catching declaratively

    We can combine the declarative nature of the operator with a desire to handle all the exceptions, by moving the body of the collect operator into and putting it before the catch operator. Collection of this flow must be triggered by a call to collect() without parameters:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun simple(): Flow<Int> = flow {
    4. for (i in 1..3) {
    5. println("Emitting $i")
    6. emit(i)
    7. }
    8. }
    9. fun main() = runBlocking<Unit> {
    10. //sampleStart
    11. simple()
    12. .onEach { value ->
    13. check(value <= 1) { "Collected $value" }
    14. println(value)
    15. }
    16. .catch { e -> println("Caught $e") }
    17. .collect()
    18. //sampleEnd
    19. }

    You can get the full code from here.

    Now we can see that a “Caught …” message is printed and so we can catch all the exceptions without explicitly using a try/catch block:

    1. Emitting 1
    2. 1
    3. Emitting 2
    4. Caught java.lang.IllegalStateException: Collected 2

    Flow completion

    When flow collection completes (normally or exceptionally) it may need to execute an action. As you may have already noticed, it can be done in two ways: imperative or declarative.

    Imperative finally block

    In addition to try/catch, a collector can also use a finally block to execute an action upon collect completion.

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun simple(): Flow<Int> = (1..3).asFlow()
    5. fun main() = runBlocking<Unit> {
    6. try {
    7. simple().collect { value -> println(value) }
    8. } finally {
    9. println("Done")
    10. }
    11. }
    12. //sampleEnd

    You can get the full code from .

    This code prints three numbers produced by the simple flow followed by a “Done” string:

    1. 1
    2. 2
    3. 3
    4. Done

    Declarative handling

    For the declarative approach, flow has intermediate operator that is invoked when the flow has completely collected.

    The previous example can be rewritten using an onCompletion operator and produces the same output:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. fun simple(): Flow<Int> = (1..3).asFlow()
    4. fun main() = runBlocking<Unit> {
    5. //sampleStart
    6. simple()
    7. .onCompletion { println("Done") }
    8. .collect { value -> println(value) }
    9. //sampleEnd
    10. }

    You can get the full code from .

    The key advantage of onCompletion is a nullable Throwable parameter of the lambda that can be used to determine whether the flow collection was completed normally or exceptionally. In the following example the simple flow throws an exception after emitting the number 1:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun simple(): Flow<Int> = flow {
    5. emit(1)
    6. throw RuntimeException()
    7. }
    8. fun main() = runBlocking<Unit> {
    9. simple()
    10. .onCompletion { cause -> if (cause != null) println("Flow completed exceptionally") }
    11. .catch { cause -> println("Caught exception") }
    12. .collect { value -> println(value) }
    13. }
    14. //sampleEnd

    You can get the full code from .

    As you may expect, it prints:

    1. 1
    2. Flow completed exceptionally
    3. Caught exception

    The onCompletion operator, unlike , does not handle the exception. As we can see from the above example code, the exception still flows downstream. It will be delivered to further onCompletion operators and can be handled with a catch operator.

    Successful completion

    Another difference with operator is that onCompletion sees all exceptions and receives a null exception only on successful completion of the upstream flow (without cancellation or failure).

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun simple(): Flow<Int> = (1..3).asFlow()
    5. fun main() = runBlocking<Unit> {
    6. simple()
    7. .onCompletion { cause -> println("Flow completed with $cause") }
    8. .collect { value ->
    9. check(value <= 1) { "Collected $value" }
    10. println(value)
    11. }
    12. }
    13. //sampleEnd

    You can get the full code from .

    We can see the completion cause is not null, because the flow was aborted due to downstream exception:

    1. 1
    2. Flow completed with java.lang.IllegalStateException: Collected 2
    3. Exception in thread "main" java.lang.IllegalStateException: Collected 2

    Imperative versus declarative

    Now we know how to collect flow, and handle its completion and exceptions in both imperative and declarative ways. The natural question here is, which approach is preferred and why? As a library, we do not advocate for any particular approach and believe that both options are valid and should be selected according to your own preferences and code style.

    Launching flow

    It is easy to use flows to represent asynchronous events that are coming from some source. In this case, we need an analogue of the addEventListener function that registers a piece of code with a reaction for incoming events and continues further work. The onEach operator can serve this role. However, onEach is an intermediate operator. We also need a terminal operator to collect the flow. Otherwise, just calling onEach has no effect.

    If we use the terminal operator after onEach, then the code after it will wait until the flow is collected:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. // Imitate a flow of events
    5. fun events(): Flow<Int> = (1..3).asFlow().onEach { delay(100) }
    6. fun main() = runBlocking<Unit> {
    7. events()
    8. .onEach { event -> println("Event: $event") }
    9. .collect() // <--- Collecting the flow waits
    10. println("Done")
    11. }
    12. //sampleEnd

    You can get the full code from here.

    As you can see, it prints:

    1. Event: 1
    2. Event: 2
    3. Event: 3
    4. Done

    The terminal operator comes in handy here. By replacing collect with launchIn we can launch a collection of the flow in a separate coroutine, so that execution of further code immediately continues:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. // Imitate a flow of events
    4. fun events(): Flow<Int> = (1..3).asFlow().onEach { delay(100) }
    5. //sampleStart
    6. fun main() = runBlocking<Unit> {
    7. events()
    8. .onEach { event -> println("Event: $event") }
    9. .launchIn(this) // <--- Launching the flow in a separate coroutine
    10. println("Done")
    11. }
    12. //sampleEnd

    You can get the full code from here.

    It prints:

    1. Done
    2. Event: 1
    3. Event: 2
    4. Event: 3

    The required parameter to launchIn must specify a in which the coroutine to collect the flow is launched. In the above example this scope comes from the runBlocking coroutine builder, so while the flow is running, this scope waits for completion of its child coroutine and keeps the main function from returning and terminating this example.

    In actual applications a scope will come from an entity with a limited lifetime. As soon as the lifetime of this entity is terminated the corresponding scope is cancelled, cancelling the collection of the corresponding flow. This way the pair of onEach { ... }.launchIn(scope) works like the addEventListener. However, there is no need for the corresponding removeEventListener function, as cancellation and structured concurrency serve this purpose.

    Note that launchIn also returns a , which can be used to cancel the corresponding flow collection coroutine only without cancelling the whole scope or to it.

    Flow cancellation checks

    For convenience, the builder performs additional ensureActive checks for cancellation on each emitted value. It means that a busy loop emitting from a flow { ... } is cancellable:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun foo(): Flow<Int> = flow {
    5. for (i in 1..5) {
    6. println("Emitting $i")
    7. emit(i)
    8. }
    9. }
    10. fun main() = runBlocking<Unit> {
    11. foo().collect { value ->
    12. if (value == 3) cancel()
    13. println(value)
    14. }
    15. }
    16. //sampleEnd

    You can get the full code from .

    We get only numbers up to 3 and a CancellationException after trying to emit number 4:

    1. Emitting 1
    2. 1
    3. Emitting 2
    4. 2
    5. Emitting 3
    6. 3
    7. Emitting 4
    8. Exception in thread "main" kotlinx.coroutines.JobCancellationException: BlockingCoroutine was cancelled; job="coroutine#1":BlockingCoroutine{Cancelled}@6d7b4f4c

    However, most other flow operators do not do additional cancellation checks on their own for performance reasons. For example, if you use extension to write the same busy loop and don’t suspend anywhere, then there are no checks for cancellation:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.flow.*
    3. //sampleStart
    4. fun main() = runBlocking<Unit> {
    5. (1..5).asFlow().collect { value ->
    6. if (value == 3) cancel()
    7. println(value)
    8. }
    9. }
    10. //sampleEnd

    All numbers from 1 to 5 are collected and cancellation gets detected only before return from runBlocking:

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. Exception in thread "main" kotlinx.coroutines.JobCancellationException: BlockingCoroutine was cancelled; job="coroutine#1":BlockingCoroutine{Cancelled}@3327bd23

    Making busy flow cancellable

    In the case where you have a busy loop with coroutines you must explicitly check for cancellation. You can add .onEach { currentCoroutineContext().ensureActive() }, but there is a ready-to-use operator provided to do that:

    You can get the full code from here.

    With the cancellable operator only the numbers from 1 to 3 are collected:

    1. 1
    2. 2
    3. 3
    4. Exception in thread "main" kotlinx.coroutines.JobCancellationException: BlockingCoroutine was cancelled; job="coroutine#1":BlockingCoroutine{Cancelled}@5ec0a365

    Flow and Reactive Streams

    For those who are familiar with Reactive Streams or reactive frameworks such as RxJava and project Reactor, design of the Flow may look very familiar.

    While being different, conceptually, Flow is a reactive stream and it is possible to convert it to the reactive (spec and TCK compliant) Publisher and vice versa. Such converters are provided by kotlinx.coroutines out-of-the-box and can be found in corresponding reactive modules (kotlinx-coroutines-reactive for Reactive Streams, kotlinx-coroutines-reactor for Project Reactor and kotlinx-coroutines-rx2/kotlinx-coroutines-rx3 for RxJava2/RxJava3). Integration modules include conversions from and to , integration with Reactor’s Context and suspension-friendly ways to work with various reactive entities.