<commit_before><!--- TEST_NAME FlowGuideTest --> 

**Table of contents**

<!--- TOC -->

* [Asynchronous Flow](#asynchronous-flow)
  * [Representing multiple values](#representing-multiple-values)
    * [Sequences](#sequences)
    * [Suspending functions](#suspending-functions)
    * [Flows](#flows)
  * [Flows are cold](#flows-are-cold)
  * [Flow cancellation basics](#flow-cancellation-basics)
  * [Flow builders](#flow-builders)
  * [Intermediate flow operators](#intermediate-flow-operators)
    * [Transform operator](#transform-operator)
    * [Size-limiting operators](#size-limiting-operators)
  * [Terminal flow operators](#terminal-flow-operators)
  * [Flows are sequential](#flows-are-sequential)
  * [Flow context](#flow-context)
    * [Wrong emission withContext](#wrong-emission-withcontext)
    * [flowOn operator](#flowon-operator)
  * [Buffering](#buffering)
    * [Conflation](#conflation)
    * [Processing the latest value](#processing-the-latest-value)
  * [Composing multiple flows](#composing-multiple-flows)
    * [Zip](#zip)
    * [Combine](#combine)
  * [Flattening flows](#flattening-flows)
    * [flatMapConcat](#flatmapconcat)
    * [flatMapMerge](#flatmapmerge)
    * [flatMapLatest](#flatmaplatest)
  * [Flow exceptions](#flow-exceptions)
    * [Collector try and catch](#collector-try-and-catch)
    * [Everything is caught](#everything-is-caught)
  * [Exception transparency](#exception-transparency)
    * [Transparent catch](#transparent-catch)
    * [Catching declaratively](#catching-declaratively)
  * [Flow completion](#flow-completion)
    * [Imperative finally block](#imperative-finally-block)
    * [Declarative handling](#declarative-handling)
    * [Successful completion](#successful-completion)
  * [Imperative versus declarative](#imperative-versus-declarative)
  * [Launching flow](#launching-flow)
  * [Flow cancellation checks](#flow-cancellation-checks)
    * [Making busy flow cancellable](#making-busy-flow-cancellable)
  * [Flow and Reactive Streams](#flow-and-reactive-streams)

<!--- END -->

## Asynchronous Flow

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

### Representing multiple values

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

<div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3">

```kotlin
fun simple(): List<Int> = listOf(1, 2, 3)
 
fun main() {
    simple().forEach { value -> println(value) } 
}
```

</div>

> You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-01.kt).

This code outputs:

```text
1
2
3
```

<!--- TEST -->

#### 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]:

<div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3">

```kotlin
fun simple(): Sequence<Int> = sequence { // sequence builder
    for (i in 1..3) {
        Thread.sleep(100) // pretend we are computing it
        yield(i) // yield next value
    }
}

fun main() {
    simple().forEach { value -> println(value) } 
}
```  

</div>

> You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-02.kt).

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

<!--- TEST 
1
2
3
-->

#### 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:

<div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3">

```kotlin
import kotlinx.coroutines.*                 
                           
//sampleStart
suspend fun simple(): List<Int> {
    delay(1000) // pretend we are doing something asynchronous here
    return listOf(1, 2, 3)
}

fun main() = runBlocking<Unit> {
    simple().forEach { value -> println(value) } 
}
//sampleEnd
```  

</div>

> You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-03.kt).

This code prints the numbers after waiting for a second.

<!--- TEST 
1
2
3
-->

#### 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 [`Flow<Int>`][Flow] type just like we would the `Sequence<Int>` type for synchronously computed values:

<div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3">

```kotlin
import kotlinx.coroutines.*<commit_msg>Update typo in flow.md (#2199)<commit_after><!--- TEST_NAME FlowGuideTest --> 

**Table of contents**

<!--- TOC -->

* [Asynchronous Flow](#asynchronous-flow)
  * [Representing multiple values](#representing-multiple-values)
    * [Sequences](#sequences)
    * [Suspending functions](#suspending-functions)
    * [Flows](#flows)
  * [Flows are cold](#flows-are-cold)
  * [Flow cancellation basics](#flow-cancellation-basics)
  * [Flow builders](#flow-builders)
  * [Intermediate flow operators](#intermediate-flow-operators)
    * [Transform operator](#transform-operator)
    * [Size-limiting operators](#size-limiting-operators)
  * [Terminal flow operators](#terminal-flow-operators)
  * [Flows are sequential](#flows-are-sequential)
  * [Flow context](#flow-context)
    * [Wrong emission withContext](#wrong-emission-withcontext)
    * [flowOn operator](#flowon-operator)
  * [Buffering](#buffering)
    * [Conflation](#conflation)
    * [Processing the latest value](#processing-the-latest-value)
  * [Composing multiple flows](#composing-multiple-flows)
    * [Zip](#zip)
    * [Combine](#combine)
  * [Flattening flows](#flattening-flows)
    * [flatMapConcat](#flatmapconcat)
    * [flatMapMerge](#flatmapmerge)
    * [flatMapLatest](#flatmaplatest)
  * [Flow exceptions](#flow-exceptions)
    * [Collector try and catch](#collector-try-and-catch)
    * [Everything is caught](#everything-is-caught)
  * [Exception transparency](#exception-transparency)
    * [Transparent catch](#transparent-catch)
    * [Catching declaratively](#catching-declaratively)
  * [Flow completion](#flow-completion)
    * [Imperative finally block](#imperative-finally-block)
    * [Declarative handling](#declarative-handling)
    * [Successful completion](#successful-completion)
  * [Imperative versus declarative](#imperative-versus-declarative)
  * [Launching flow](#launching-flow)
  * [Flow cancellation checks](#flow-cancellation-checks)
    * [Making busy flow cancellable](#making-busy-flow-cancellable)
  * [Flow and Reactive Streams](#flow-and-reactive-streams)

<!--- END -->

## Asynchronous Flow

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

### Representing multiple values

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

<div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3">

```kotlin
fun simple(): List<Int> = listOf(1, 2, 3)
 
fun main() {
    simple().forEach { value -> println(value) } 
}
```

</div>

> You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-01.kt).

This code outputs:

```text
1
2
3
```

<!--- TEST -->

#### 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]:

<div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3">

```kotlin
fun simple(): Sequence<Int> = sequence { // sequence builder
    for (i in 1..3) {
        Thread.sleep(100) // pretend we are computing it
        yield(i) // yield next value
    }
}

fun main() {
    simple().forEach { value -> println(value) } 
}
```  

</div>

> You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-02.kt).

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

<!--- TEST 
1
2
3
-->

#### 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:

<div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3">

```kotlin
import kotlinx.coroutines.*                 
                           
//sampleStart
suspend fun simple(): List<Int> {
    delay(1000) // pretend we are doing something asynchronous here
    return listOf(1, 2, 3)
}

fun main() = runBlocking<Unit> {
    simple().forEach { value -> println(value) } 
}
//sampleEnd
```  

</div>

> You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-03.kt).

This code prints the numbers after waiting for a second.

<!--- TEST 
1
2
3
-->

#### 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 [`Flow<Int>`][Flow] type just like we would use the `Sequence<Int>` type for synchronously computed values:

<div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3">

```kotlin
import kotlinx.coroutines.*
{'fraction_non_alphanumeric': 0.14086229742126186, 'fraction_numerical': 0.010192640913260626, 'mean_word_length': 4.0708010335917315, 'pattern_counts': {'":': 0, '<': 43, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1295742', 'n_tokens_mistral': 3229, 'n_tokens_neox': 2982, 'n_words': 870}