Roman Elizarov | 660c2d7 | 2020-02-14 13:18:37 +0300 | [diff] [blame] | 1 | <!--- TEST_NAME FlowGuideTest --> |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 2 | |
| 3 | **Table of contents** |
| 4 | |
| 5 | <!--- TOC --> |
| 6 | |
| 7 | * [Asynchronous Flow](#asynchronous-flow) |
| 8 | * [Representing multiple values](#representing-multiple-values) |
| 9 | * [Sequences](#sequences) |
| 10 | * [Suspending functions](#suspending-functions) |
| 11 | * [Flows](#flows) |
| 12 | * [Flows are cold](#flows-are-cold) |
Roman Elizarov | 9bbb669 | 2020-06-03 12:02:17 +0300 | [diff] [blame^] | 13 | * [Flow cancellation basics](#flow-cancellation-basics) |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 14 | * [Flow builders](#flow-builders) |
| 15 | * [Intermediate flow operators](#intermediate-flow-operators) |
| 16 | * [Transform operator](#transform-operator) |
| 17 | * [Size-limiting operators](#size-limiting-operators) |
| 18 | * [Terminal flow operators](#terminal-flow-operators) |
| 19 | * [Flows are sequential](#flows-are-sequential) |
| 20 | * [Flow context](#flow-context) |
| 21 | * [Wrong emission withContext](#wrong-emission-withcontext) |
| 22 | * [flowOn operator](#flowon-operator) |
| 23 | * [Buffering](#buffering) |
| 24 | * [Conflation](#conflation) |
| 25 | * [Processing the latest value](#processing-the-latest-value) |
| 26 | * [Composing multiple flows](#composing-multiple-flows) |
| 27 | * [Zip](#zip) |
| 28 | * [Combine](#combine) |
| 29 | * [Flattening flows](#flattening-flows) |
| 30 | * [flatMapConcat](#flatmapconcat) |
| 31 | * [flatMapMerge](#flatmapmerge) |
| 32 | * [flatMapLatest](#flatmaplatest) |
| 33 | * [Flow exceptions](#flow-exceptions) |
| 34 | * [Collector try and catch](#collector-try-and-catch) |
| 35 | * [Everything is caught](#everything-is-caught) |
| 36 | * [Exception transparency](#exception-transparency) |
| 37 | * [Transparent catch](#transparent-catch) |
| 38 | * [Catching declaratively](#catching-declaratively) |
| 39 | * [Flow completion](#flow-completion) |
| 40 | * [Imperative finally block](#imperative-finally-block) |
| 41 | * [Declarative handling](#declarative-handling) |
Roman Elizarov | eb4e7d3 | 2020-04-27 15:04:00 +0300 | [diff] [blame] | 42 | * [Successful completion](#successful-completion) |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 43 | * [Imperative versus declarative](#imperative-versus-declarative) |
| 44 | * [Launching flow](#launching-flow) |
Roman Elizarov | 9bbb669 | 2020-06-03 12:02:17 +0300 | [diff] [blame^] | 45 | * [Flow cancellation checks](#flow-cancellation-checks) |
| 46 | * [Making busy flow cancellable](#making-busy-flow-cancellable) |
Vsevolod Tolstopyatov | c99704a | 2019-09-24 19:30:49 +0300 | [diff] [blame] | 47 | * [Flow and Reactive Streams](#flow-and-reactive-streams) |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 48 | |
Roman Elizarov | 660c2d7 | 2020-02-14 13:18:37 +0300 | [diff] [blame] | 49 | <!--- END --> |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 50 | |
| 51 | ## Asynchronous Flow |
| 52 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 53 | Suspending functions asynchronously returns a single value, but how can we return |
| 54 | multiple asynchronously computed values? This is where Kotlin Flows come in. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 55 | |
| 56 | ### Representing multiple values |
| 57 | |
| 58 | Multiple values can be represented in Kotlin using [collections]. |
| 59 | For example, we can have a function `foo()` that returns a [List] |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 60 | of three numbers and then print them all using [forEach]: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 61 | |
| 62 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 63 | |
| 64 | ```kotlin |
| 65 | fun foo(): List<Int> = listOf(1, 2, 3) |
| 66 | |
| 67 | fun main() { |
| 68 | foo().forEach { value -> println(value) } |
| 69 | } |
| 70 | ``` |
| 71 | |
| 72 | </div> |
| 73 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 74 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-01.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 75 | |
| 76 | This code outputs: |
| 77 | |
| 78 | ```text |
| 79 | 1 |
| 80 | 2 |
| 81 | 3 |
| 82 | ``` |
| 83 | |
| 84 | <!--- TEST --> |
| 85 | |
| 86 | #### Sequences |
| 87 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 88 | If we are computing the numbers with some CPU-consuming blocking code |
| 89 | (each computation taking 100ms), then we can represent the numbers using a [Sequence]: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 90 | |
| 91 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 92 | |
| 93 | ```kotlin |
| 94 | fun foo(): Sequence<Int> = sequence { // sequence builder |
| 95 | for (i in 1..3) { |
| 96 | Thread.sleep(100) // pretend we are computing it |
| 97 | yield(i) // yield next value |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | fun main() { |
| 102 | foo().forEach { value -> println(value) } |
| 103 | } |
| 104 | ``` |
| 105 | |
| 106 | </div> |
| 107 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 108 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-02.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 109 | |
| 110 | This code outputs the same numbers, but it waits 100ms before printing each one. |
| 111 | |
| 112 | <!--- TEST |
| 113 | 1 |
| 114 | 2 |
| 115 | 3 |
| 116 | --> |
| 117 | |
| 118 | #### Suspending functions |
| 119 | |
| 120 | However, this computation blocks the main thread that is running the code. |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 121 | When these values are computed by asynchronous code we can mark the function `foo` with a `suspend` modifier, |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 122 | so that it can perform its work without blocking and return the result as a list: |
| 123 | |
| 124 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 125 | |
| 126 | ```kotlin |
| 127 | import kotlinx.coroutines.* |
| 128 | |
| 129 | //sampleStart |
| 130 | suspend fun foo(): List<Int> { |
| 131 | delay(1000) // pretend we are doing something asynchronous here |
| 132 | return listOf(1, 2, 3) |
| 133 | } |
| 134 | |
| 135 | fun main() = runBlocking<Unit> { |
| 136 | foo().forEach { value -> println(value) } |
| 137 | } |
| 138 | //sampleEnd |
| 139 | ``` |
| 140 | |
| 141 | </div> |
| 142 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 143 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-03.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 144 | |
| 145 | This code prints the numbers after waiting for a second. |
| 146 | |
| 147 | <!--- TEST |
| 148 | 1 |
| 149 | 2 |
| 150 | 3 |
| 151 | --> |
| 152 | |
| 153 | #### Flows |
| 154 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 155 | Using the `List<Int>` result type, means we can only return all the values at once. To represent |
| 156 | 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: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 157 | |
| 158 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 159 | |
| 160 | ```kotlin |
| 161 | import kotlinx.coroutines.* |
| 162 | import kotlinx.coroutines.flow.* |
| 163 | |
| 164 | //sampleStart |
| 165 | fun foo(): Flow<Int> = flow { // flow builder |
| 166 | for (i in 1..3) { |
| 167 | delay(100) // pretend we are doing something useful here |
| 168 | emit(i) // emit next value |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | fun main() = runBlocking<Unit> { |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 173 | // Launch a concurrent coroutine to check if the main thread is blocked |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 174 | launch { |
| 175 | for (k in 1..3) { |
| 176 | println("I'm not blocked $k") |
| 177 | delay(100) |
| 178 | } |
| 179 | } |
| 180 | // Collect the flow |
| 181 | foo().collect { value -> println(value) } |
| 182 | } |
| 183 | //sampleEnd |
| 184 | ``` |
| 185 | |
| 186 | </div> |
| 187 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 188 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-04.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 189 | |
| 190 | This code waits 100ms before printing each number without blocking the main thread. This is verified |
| 191 | by printing "I'm not blocked" every 100ms from a separate coroutine that is running in the main thread: |
| 192 | |
| 193 | ```text |
| 194 | I'm not blocked 1 |
| 195 | 1 |
| 196 | I'm not blocked 2 |
| 197 | 2 |
| 198 | I'm not blocked 3 |
| 199 | 3 |
| 200 | ``` |
| 201 | |
| 202 | <!--- TEST --> |
| 203 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 204 | Notice the following differences in the code with the [Flow] from the earlier examples: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 205 | |
| 206 | * A builder function for [Flow] type is called [flow]. |
| 207 | * Code inside the `flow { ... }` builder block can suspend. |
| 208 | * The function `foo()` is no longer marked with `suspend` modifier. |
| 209 | * Values are _emitted_ from the flow using [emit][FlowCollector.emit] function. |
| 210 | * Values are _collected_ from the flow using [collect][collect] function. |
| 211 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 212 | > We can replace [delay] with `Thread.sleep` in the body of `foo`'s `flow { ... }` and see that the main |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 213 | thread is blocked in this case. |
| 214 | |
| 215 | ### Flows are cold |
| 216 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 217 | Flows are _cold_ streams similar to sequences — the code inside a [flow] builder does not |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 218 | run until the flow is collected. This becomes clear in the following example: |
| 219 | |
| 220 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 221 | |
| 222 | ```kotlin |
| 223 | import kotlinx.coroutines.* |
| 224 | import kotlinx.coroutines.flow.* |
| 225 | |
| 226 | //sampleStart |
| 227 | fun foo(): Flow<Int> = flow { |
| 228 | println("Flow started") |
| 229 | for (i in 1..3) { |
| 230 | delay(100) |
| 231 | emit(i) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | fun main() = runBlocking<Unit> { |
| 236 | println("Calling foo...") |
| 237 | val flow = foo() |
| 238 | println("Calling collect...") |
| 239 | flow.collect { value -> println(value) } |
| 240 | println("Calling collect again...") |
| 241 | flow.collect { value -> println(value) } |
| 242 | } |
| 243 | //sampleEnd |
| 244 | ``` |
| 245 | |
| 246 | </div> |
| 247 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 248 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-05.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 249 | |
| 250 | Which prints: |
| 251 | |
| 252 | ```text |
| 253 | Calling foo... |
| 254 | Calling collect... |
| 255 | Flow started |
| 256 | 1 |
| 257 | 2 |
| 258 | 3 |
| 259 | Calling collect again... |
| 260 | Flow started |
| 261 | 1 |
| 262 | 2 |
| 263 | 3 |
| 264 | ``` |
| 265 | |
| 266 | <!--- TEST --> |
| 267 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 268 | This is a key reason the `foo()` function (which returns a flow) is not marked with `suspend` modifier. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 269 | By itself, `foo()` returns quickly and does not wait for anything. The flow starts every time it is collected, |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 270 | that is why we see "Flow started" when we call `collect` again. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 271 | |
Roman Elizarov | 9bbb669 | 2020-06-03 12:02:17 +0300 | [diff] [blame^] | 272 | ### Flow cancellation basics |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 273 | |
Roman Elizarov | 9bbb669 | 2020-06-03 12:02:17 +0300 | [diff] [blame^] | 274 | Flow adheres to the general cooperative cancellation of coroutines. As usual, flow collection can be |
| 275 | cancelled when the flow is suspended in a cancellable suspending function (like [delay]). |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 276 | The following example shows how the flow gets cancelled on a timeout when running in a [withTimeoutOrNull] block |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 277 | and stops executing its code: |
| 278 | |
| 279 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 280 | |
| 281 | ```kotlin |
| 282 | import kotlinx.coroutines.* |
| 283 | import kotlinx.coroutines.flow.* |
| 284 | |
| 285 | //sampleStart |
| 286 | fun foo(): Flow<Int> = flow { |
| 287 | for (i in 1..3) { |
| 288 | delay(100) |
| 289 | println("Emitting $i") |
| 290 | emit(i) |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | fun main() = runBlocking<Unit> { |
| 295 | withTimeoutOrNull(250) { // Timeout after 250ms |
| 296 | foo().collect { value -> println(value) } |
| 297 | } |
| 298 | println("Done") |
| 299 | } |
| 300 | //sampleEnd |
| 301 | ``` |
| 302 | |
| 303 | </div> |
| 304 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 305 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-06.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 306 | |
| 307 | Notice how only two numbers get emitted by the flow in `foo()` function, producing the following output: |
| 308 | |
| 309 | ```text |
| 310 | Emitting 1 |
| 311 | 1 |
| 312 | Emitting 2 |
| 313 | 2 |
| 314 | Done |
| 315 | ``` |
| 316 | |
| 317 | <!--- TEST --> |
| 318 | |
Roman Elizarov | 9bbb669 | 2020-06-03 12:02:17 +0300 | [diff] [blame^] | 319 | See [Flow cancellation checks](#flow-cancellation-checks) section for more details. |
| 320 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 321 | ### Flow builders |
| 322 | |
| 323 | The `flow { ... }` builder from the previous examples is the most basic one. There are other builders for |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 324 | easier declaration of flows: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 325 | |
| 326 | * [flowOf] builder that defines a flow emitting a fixed set of values. |
| 327 | * Various collections and sequences can be converted to flows using `.asFlow()` extension functions. |
| 328 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 329 | So, the example that prints the numbers from 1 to 3 from a flow can be written as: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 330 | |
| 331 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 332 | |
| 333 | ```kotlin |
| 334 | import kotlinx.coroutines.* |
| 335 | import kotlinx.coroutines.flow.* |
| 336 | |
| 337 | fun main() = runBlocking<Unit> { |
| 338 | //sampleStart |
| 339 | // Convert an integer range to a flow |
| 340 | (1..3).asFlow().collect { value -> println(value) } |
| 341 | //sampleEnd |
| 342 | } |
| 343 | ``` |
| 344 | |
| 345 | </div> |
| 346 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 347 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-07.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 348 | |
| 349 | <!--- TEST |
| 350 | 1 |
| 351 | 2 |
| 352 | 3 |
| 353 | --> |
| 354 | |
| 355 | ### Intermediate flow operators |
| 356 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 357 | Flows can be transformed with operators, just as you would with collections and sequences. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 358 | Intermediate operators are applied to an upstream flow and return a downstream flow. |
| 359 | These operators are cold, just like flows are. A call to such an operator is not |
| 360 | a suspending function itself. It works quickly, returning the definition of a new transformed flow. |
| 361 | |
| 362 | The basic operators have familiar names like [map] and [filter]. |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 363 | The important difference to sequences is that blocks of |
| 364 | code inside these operators can call suspending functions. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 365 | |
| 366 | For example, a flow of incoming requests can be |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 367 | mapped to the results with the [map] operator, even when performing a request is a long-running |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 368 | operation that is implemented by a suspending function: |
| 369 | |
| 370 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 371 | |
| 372 | ```kotlin |
| 373 | import kotlinx.coroutines.* |
| 374 | import kotlinx.coroutines.flow.* |
| 375 | |
| 376 | //sampleStart |
| 377 | suspend fun performRequest(request: Int): String { |
| 378 | delay(1000) // imitate long-running asynchronous work |
| 379 | return "response $request" |
| 380 | } |
| 381 | |
| 382 | fun main() = runBlocking<Unit> { |
| 383 | (1..3).asFlow() // a flow of requests |
| 384 | .map { request -> performRequest(request) } |
| 385 | .collect { response -> println(response) } |
| 386 | } |
| 387 | //sampleEnd |
| 388 | ``` |
| 389 | |
| 390 | </div> |
| 391 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 392 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-08.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 393 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 394 | It produces the following three lines, each line appearing after each second: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 395 | |
| 396 | ```text |
| 397 | response 1 |
| 398 | response 2 |
| 399 | response 3 |
| 400 | ``` |
| 401 | |
| 402 | <!--- TEST --> |
| 403 | |
| 404 | #### Transform operator |
| 405 | |
| 406 | Among the flow transformation operators, the most general one is called [transform]. It can be used to imitate |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 407 | simple transformations like [map] and [filter], as well as implement more complex transformations. |
| 408 | Using the `transform` operator, we can [emit][FlowCollector.emit] arbitrary values an arbitrary number of times. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 409 | |
| 410 | For example, using `transform` we can emit a string before performing a long-running asynchronous request |
| 411 | and follow it with a response: |
| 412 | |
| 413 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 414 | |
| 415 | ```kotlin |
| 416 | import kotlinx.coroutines.* |
| 417 | import kotlinx.coroutines.flow.* |
| 418 | |
| 419 | suspend fun performRequest(request: Int): String { |
| 420 | delay(1000) // imitate long-running asynchronous work |
| 421 | return "response $request" |
| 422 | } |
| 423 | |
| 424 | fun main() = runBlocking<Unit> { |
| 425 | //sampleStart |
| 426 | (1..3).asFlow() // a flow of requests |
| 427 | .transform { request -> |
| 428 | emit("Making request $request") |
| 429 | emit(performRequest(request)) |
| 430 | } |
| 431 | .collect { response -> println(response) } |
| 432 | //sampleEnd |
| 433 | } |
| 434 | ``` |
| 435 | |
| 436 | </div> |
| 437 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 438 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-09.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 439 | |
| 440 | The output of this code is: |
| 441 | |
| 442 | ```text |
| 443 | Making request 1 |
| 444 | response 1 |
| 445 | Making request 2 |
| 446 | response 2 |
| 447 | Making request 3 |
| 448 | response 3 |
| 449 | ``` |
| 450 | |
| 451 | <!--- TEST --> |
| 452 | |
| 453 | #### Size-limiting operators |
| 454 | |
| 455 | Size-limiting intermediate operators like [take] cancel the execution of the flow when the corresponding limit |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 456 | is reached. Cancellation in coroutines is always performed by throwing an exception, so that all the resource-management |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 457 | functions (like `try { ... } finally { ... }` blocks) operate normally in case of cancellation: |
| 458 | |
| 459 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 460 | |
| 461 | ```kotlin |
| 462 | import kotlinx.coroutines.* |
| 463 | import kotlinx.coroutines.flow.* |
| 464 | |
| 465 | //sampleStart |
| 466 | fun numbers(): Flow<Int> = flow { |
| 467 | try { |
| 468 | emit(1) |
| 469 | emit(2) |
| 470 | println("This line will not execute") |
| 471 | emit(3) |
| 472 | } finally { |
| 473 | println("Finally in numbers") |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | fun main() = runBlocking<Unit> { |
| 478 | numbers() |
| 479 | .take(2) // take only the first two |
| 480 | .collect { value -> println(value) } |
| 481 | } |
| 482 | //sampleEnd |
| 483 | ``` |
| 484 | |
| 485 | </div> |
| 486 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 487 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-10.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 488 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 489 | The output of this code clearly shows that the execution of the `flow { ... }` body in the `numbers()` function |
| 490 | stopped after emitting the second number: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 491 | |
| 492 | ```text |
| 493 | 1 |
| 494 | 2 |
| 495 | Finally in numbers |
| 496 | ``` |
| 497 | |
| 498 | <!--- TEST --> |
| 499 | |
| 500 | ### Terminal flow operators |
| 501 | |
| 502 | Terminal operators on flows are _suspending functions_ that start a collection of the flow. |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 503 | The [collect] operator is the most basic one, but there are other terminal operators, which can make it easier: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 504 | |
| 505 | * Conversion to various collections like [toList] and [toSet]. |
| 506 | * Operators to get the [first] value and to ensure that a flow emits a [single] value. |
| 507 | * Reducing a flow to a value with [reduce] and [fold]. |
| 508 | |
| 509 | For example: |
| 510 | |
| 511 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 512 | |
| 513 | ```kotlin |
| 514 | import kotlinx.coroutines.* |
| 515 | import kotlinx.coroutines.flow.* |
| 516 | |
| 517 | fun main() = runBlocking<Unit> { |
| 518 | //sampleStart |
| 519 | val sum = (1..5).asFlow() |
| 520 | .map { it * it } // squares of numbers from 1 to 5 |
| 521 | .reduce { a, b -> a + b } // sum them (terminal operator) |
| 522 | println(sum) |
| 523 | //sampleEnd |
| 524 | } |
| 525 | ``` |
| 526 | |
| 527 | </div> |
| 528 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 529 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-11.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 530 | |
| 531 | Prints a single number: |
| 532 | |
| 533 | ```text |
| 534 | 55 |
| 535 | ``` |
| 536 | |
| 537 | <!--- TEST --> |
| 538 | |
| 539 | ### Flows are sequential |
| 540 | |
| 541 | Each individual collection of a flow is performed sequentially unless special operators that operate |
| 542 | on multiple flows are used. The collection works directly in the coroutine that calls a terminal operator. |
| 543 | No new coroutines are launched by default. |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 544 | Each emitted value is processed by all the intermediate operators from |
| 545 | upstream to downstream and is then delivered to the terminal operator after. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 546 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 547 | See the following example that filters the even integers and maps them to strings: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 548 | |
| 549 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 550 | |
| 551 | ```kotlin |
| 552 | import kotlinx.coroutines.* |
| 553 | import kotlinx.coroutines.flow.* |
| 554 | |
| 555 | fun main() = runBlocking<Unit> { |
| 556 | //sampleStart |
| 557 | (1..5).asFlow() |
| 558 | .filter { |
| 559 | println("Filter $it") |
| 560 | it % 2 == 0 |
| 561 | } |
| 562 | .map { |
| 563 | println("Map $it") |
| 564 | "string $it" |
| 565 | }.collect { |
| 566 | println("Collect $it") |
| 567 | } |
| 568 | //sampleEnd |
| 569 | } |
| 570 | ``` |
| 571 | |
| 572 | </div> |
| 573 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 574 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-12.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 575 | |
| 576 | Producing: |
| 577 | |
| 578 | ```text |
| 579 | Filter 1 |
| 580 | Filter 2 |
| 581 | Map 2 |
| 582 | Collect string 2 |
| 583 | Filter 3 |
| 584 | Filter 4 |
| 585 | Map 4 |
| 586 | Collect string 4 |
| 587 | Filter 5 |
| 588 | ``` |
| 589 | |
| 590 | <!--- TEST --> |
| 591 | |
| 592 | ### Flow context |
| 593 | |
| 594 | Collection of a flow always happens in the context of the calling coroutine. For example, if there is |
| 595 | a `foo` flow, then the following code runs in the context specified |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 596 | by the author of this code, regardless of the implementation details of the `foo` flow: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 597 | |
| 598 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 599 | |
| 600 | ```kotlin |
| 601 | withContext(context) { |
| 602 | foo.collect { value -> |
| 603 | println(value) // run in the specified context |
| 604 | } |
| 605 | } |
| 606 | ``` |
| 607 | |
| 608 | </div> |
| 609 | |
| 610 | <!--- CLEAR --> |
| 611 | |
| 612 | This property of a flow is called _context preservation_. |
| 613 | |
| 614 | So, by default, code in the `flow { ... }` builder runs in the context that is provided by a collector |
| 615 | of the corresponding flow. For example, consider the implementation of `foo` that prints the thread |
| 616 | it is called on and emits three numbers: |
| 617 | |
| 618 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 619 | |
| 620 | ```kotlin |
| 621 | import kotlinx.coroutines.* |
| 622 | import kotlinx.coroutines.flow.* |
| 623 | |
| 624 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 625 | |
| 626 | //sampleStart |
| 627 | fun foo(): Flow<Int> = flow { |
| 628 | log("Started foo flow") |
| 629 | for (i in 1..3) { |
| 630 | emit(i) |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | fun main() = runBlocking<Unit> { |
| 635 | foo().collect { value -> log("Collected $value") } |
| 636 | } |
| 637 | //sampleEnd |
| 638 | ``` |
| 639 | |
| 640 | </div> |
| 641 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 642 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-13.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 643 | |
| 644 | Running this code produces: |
| 645 | |
| 646 | ```text |
| 647 | [main @coroutine#1] Started foo flow |
| 648 | [main @coroutine#1] Collected 1 |
| 649 | [main @coroutine#1] Collected 2 |
| 650 | [main @coroutine#1] Collected 3 |
| 651 | ``` |
| 652 | |
| 653 | <!--- TEST FLEXIBLE_THREAD --> |
| 654 | |
| 655 | Since `foo().collect` is called from the main thread, the body of `foo`'s flow is also called in the main thread. |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 656 | This is the perfect default for fast-running or asynchronous code that does not care about the execution context and |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 657 | does not block the caller. |
| 658 | |
| 659 | #### Wrong emission withContext |
| 660 | |
| 661 | However, the long-running CPU-consuming code might need to be executed in the context of [Dispatchers.Default] and UI-updating |
| 662 | code might need to be executed in the context of [Dispatchers.Main]. Usually, [withContext] is used |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 663 | to change the context in the code using Kotlin coroutines, but code in the `flow { ... }` builder has to honor the context |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 664 | preservation property and is not allowed to [emit][FlowCollector.emit] from a different context. |
| 665 | |
| 666 | Try running the following code: |
| 667 | |
| 668 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 669 | |
| 670 | ```kotlin |
| 671 | import kotlinx.coroutines.* |
| 672 | import kotlinx.coroutines.flow.* |
| 673 | |
| 674 | //sampleStart |
| 675 | fun foo(): Flow<Int> = flow { |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 676 | // The WRONG way to change context for CPU-consuming code in flow builder |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 677 | kotlinx.coroutines.withContext(Dispatchers.Default) { |
| 678 | for (i in 1..3) { |
| 679 | Thread.sleep(100) // pretend we are computing it in CPU-consuming way |
| 680 | emit(i) // emit next value |
| 681 | } |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | fun main() = runBlocking<Unit> { |
| 686 | foo().collect { value -> println(value) } |
| 687 | } |
| 688 | //sampleEnd |
| 689 | ``` |
| 690 | |
| 691 | </div> |
| 692 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 693 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-14.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 694 | |
| 695 | This code produces the following exception: |
| 696 | |
Vsevolod Tolstopyatov | 83943ef | 2019-10-22 19:26:50 +0300 | [diff] [blame] | 697 | ```text |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 698 | Exception in thread "main" java.lang.IllegalStateException: Flow invariant is violated: |
| 699 | Flow was collected in [CoroutineId(1), "coroutine#1":BlockingCoroutine{Active}@5511c7f8, BlockingEventLoop@2eac3323], |
| 700 | but emission happened in [CoroutineId(1), "coroutine#1":DispatchedCoroutine{Active}@2dae0000, DefaultDispatcher]. |
| 701 | Please refer to 'flow' documentation or use 'flowOn' instead |
| 702 | at ... |
Vsevolod Tolstopyatov | 83943ef | 2019-10-22 19:26:50 +0300 | [diff] [blame] | 703 | ``` |
| 704 | |
| 705 | <!--- TEST EXCEPTION --> |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 706 | |
| 707 | #### flowOn operator |
| 708 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 709 | The exception refers to the [flowOn] function that shall be used to change the context of the flow emission. |
| 710 | The correct way to change the context of a flow is shown in the example below, which also prints the |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 711 | names of the corresponding threads to show how it all works: |
| 712 | |
| 713 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 714 | |
| 715 | ```kotlin |
| 716 | import kotlinx.coroutines.* |
| 717 | import kotlinx.coroutines.flow.* |
| 718 | |
| 719 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 720 | |
| 721 | //sampleStart |
| 722 | fun foo(): Flow<Int> = flow { |
| 723 | for (i in 1..3) { |
| 724 | Thread.sleep(100) // pretend we are computing it in CPU-consuming way |
| 725 | log("Emitting $i") |
| 726 | emit(i) // emit next value |
| 727 | } |
| 728 | }.flowOn(Dispatchers.Default) // RIGHT way to change context for CPU-consuming code in flow builder |
| 729 | |
| 730 | fun main() = runBlocking<Unit> { |
| 731 | foo().collect { value -> |
| 732 | log("Collected $value") |
| 733 | } |
| 734 | } |
| 735 | //sampleEnd |
| 736 | ``` |
| 737 | |
| 738 | </div> |
| 739 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 740 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-15.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 741 | |
| 742 | Notice how `flow { ... }` works in the background thread, while collection happens in the main thread: |
| 743 | |
| 744 | <!--- TEST FLEXIBLE_THREAD |
| 745 | [DefaultDispatcher-worker-1 @coroutine#2] Emitting 1 |
| 746 | [main @coroutine#1] Collected 1 |
| 747 | [DefaultDispatcher-worker-1 @coroutine#2] Emitting 2 |
| 748 | [main @coroutine#1] Collected 2 |
| 749 | [DefaultDispatcher-worker-1 @coroutine#2] Emitting 3 |
| 750 | [main @coroutine#1] Collected 3 |
| 751 | --> |
| 752 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 753 | Another thing to observe here is that the [flowOn] operator has changed the default sequential nature of the flow. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 754 | Now collection happens in one coroutine ("coroutine#1") and emission happens in another coroutine |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 755 | ("coroutine#2") that is running in another thread concurrently with the collecting coroutine. The [flowOn] operator |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 756 | creates another coroutine for an upstream flow when it has to change the [CoroutineDispatcher] in its context. |
| 757 | |
| 758 | ### Buffering |
| 759 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 760 | Running different parts of a flow in different coroutines can be helpful from the standpoint of the overall time it takes |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 761 | to collect the flow, especially when long-running asynchronous operations are involved. For example, consider a case when |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 762 | the emission by `foo()` flow is slow, taking 100 ms to produce an element; and collector is also slow, |
| 763 | taking 300 ms to process an element. Let's see how long it takes to collect such a flow with three numbers: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 764 | |
| 765 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 766 | |
| 767 | ```kotlin |
| 768 | import kotlinx.coroutines.* |
| 769 | import kotlinx.coroutines.flow.* |
| 770 | import kotlin.system.* |
| 771 | |
| 772 | //sampleStart |
| 773 | fun foo(): Flow<Int> = flow { |
| 774 | for (i in 1..3) { |
| 775 | delay(100) // pretend we are asynchronously waiting 100 ms |
| 776 | emit(i) // emit next value |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | fun main() = runBlocking<Unit> { |
| 781 | val time = measureTimeMillis { |
| 782 | foo().collect { value -> |
| 783 | delay(300) // pretend we are processing it for 300 ms |
| 784 | println(value) |
| 785 | } |
| 786 | } |
| 787 | println("Collected in $time ms") |
| 788 | } |
| 789 | //sampleEnd |
| 790 | ``` |
| 791 | |
| 792 | </div> |
| 793 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 794 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-16.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 795 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 796 | It produces something like this, with the whole collection taking around 1200 ms (three numbers, 400 ms for each): |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 797 | |
| 798 | ```text |
| 799 | 1 |
| 800 | 2 |
| 801 | 3 |
| 802 | Collected in 1220 ms |
| 803 | ``` |
| 804 | |
| 805 | <!--- TEST ARBITRARY_TIME --> |
| 806 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 807 | We can use a [buffer] operator on a flow to run emitting code of `foo()` concurrently with collecting code, |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 808 | as opposed to running them sequentially: |
| 809 | |
| 810 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 811 | |
| 812 | ```kotlin |
| 813 | import kotlinx.coroutines.* |
| 814 | import kotlinx.coroutines.flow.* |
| 815 | import kotlin.system.* |
| 816 | |
| 817 | fun foo(): Flow<Int> = flow { |
| 818 | for (i in 1..3) { |
| 819 | delay(100) // pretend we are asynchronously waiting 100 ms |
| 820 | emit(i) // emit next value |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | fun main() = runBlocking<Unit> { |
| 825 | //sampleStart |
| 826 | val time = measureTimeMillis { |
| 827 | foo() |
| 828 | .buffer() // buffer emissions, don't wait |
| 829 | .collect { value -> |
| 830 | delay(300) // pretend we are processing it for 300 ms |
| 831 | println(value) |
| 832 | } |
| 833 | } |
| 834 | println("Collected in $time ms") |
| 835 | //sampleEnd |
| 836 | } |
| 837 | ``` |
| 838 | |
| 839 | </div> |
| 840 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 841 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-17.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 842 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 843 | It produces the same numbers just faster, as we have effectively created a processing pipeline, |
| 844 | having to only wait 100 ms for the first number and then spending only 300 ms to process |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 845 | each number. This way it takes around 1000 ms to run: |
| 846 | |
| 847 | ```text |
| 848 | 1 |
| 849 | 2 |
| 850 | 3 |
| 851 | Collected in 1071 ms |
| 852 | ``` |
| 853 | |
| 854 | <!--- TEST ARBITRARY_TIME --> |
| 855 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 856 | > Note that the [flowOn] operator uses the same buffering mechanism when it has to change a [CoroutineDispatcher], |
| 857 | but here we explicitly request buffering without changing the execution context. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 858 | |
| 859 | #### Conflation |
| 860 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 861 | When a flow represents partial results of the operation or operation status updates, it may not be necessary |
| 862 | to process each value, but instead, only most recent ones. In this case, the [conflate] operator can be used to skip |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 863 | intermediate values when a collector is too slow to process them. Building on the previous example: |
| 864 | |
| 865 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 866 | |
| 867 | ```kotlin |
| 868 | import kotlinx.coroutines.* |
| 869 | import kotlinx.coroutines.flow.* |
| 870 | import kotlin.system.* |
| 871 | |
| 872 | fun foo(): Flow<Int> = flow { |
| 873 | for (i in 1..3) { |
| 874 | delay(100) // pretend we are asynchronously waiting 100 ms |
| 875 | emit(i) // emit next value |
| 876 | } |
| 877 | } |
| 878 | |
| 879 | fun main() = runBlocking<Unit> { |
| 880 | //sampleStart |
| 881 | val time = measureTimeMillis { |
| 882 | foo() |
| 883 | .conflate() // conflate emissions, don't process each one |
| 884 | .collect { value -> |
| 885 | delay(300) // pretend we are processing it for 300 ms |
| 886 | println(value) |
| 887 | } |
| 888 | } |
| 889 | println("Collected in $time ms") |
| 890 | //sampleEnd |
| 891 | } |
| 892 | ``` |
| 893 | |
| 894 | </div> |
| 895 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 896 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-18.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 897 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 898 | We see that while the first number was still being processed the second, and third were already produced, so |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 899 | the second one was _conflated_ and only the most recent (the third one) was delivered to the collector: |
| 900 | |
| 901 | ```text |
| 902 | 1 |
| 903 | 3 |
| 904 | Collected in 758 ms |
| 905 | ``` |
| 906 | |
| 907 | <!--- TEST ARBITRARY_TIME --> |
| 908 | |
| 909 | #### Processing the latest value |
| 910 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 911 | Conflation is one way to speed up processing when both the emitter and collector are slow. It does it by dropping emitted values. |
| 912 | The other way is to cancel a slow collector and restart it every time a new value is emitted. There is |
| 913 | a family of `xxxLatest` operators that perform the same essential logic of a `xxx` operator, but cancel the |
| 914 | code in their block on a new value. Let's try changing [conflate] to [collectLatest] in the previous example: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 915 | |
| 916 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 917 | |
| 918 | ```kotlin |
| 919 | import kotlinx.coroutines.* |
| 920 | import kotlinx.coroutines.flow.* |
| 921 | import kotlin.system.* |
| 922 | |
| 923 | fun foo(): Flow<Int> = flow { |
| 924 | for (i in 1..3) { |
| 925 | delay(100) // pretend we are asynchronously waiting 100 ms |
| 926 | emit(i) // emit next value |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | fun main() = runBlocking<Unit> { |
| 931 | //sampleStart |
| 932 | val time = measureTimeMillis { |
| 933 | foo() |
| 934 | .collectLatest { value -> // cancel & restart on the latest value |
| 935 | println("Collecting $value") |
| 936 | delay(300) // pretend we are processing it for 300 ms |
| 937 | println("Done $value") |
| 938 | } |
| 939 | } |
| 940 | println("Collected in $time ms") |
| 941 | //sampleEnd |
| 942 | } |
| 943 | ``` |
| 944 | |
| 945 | </div> |
| 946 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 947 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-19.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 948 | |
| 949 | Since the body of [collectLatest] takes 300 ms, but new values are emitted every 100 ms, we see that the block |
| 950 | is run on every value, but completes only for the last value: |
| 951 | |
| 952 | ```text |
| 953 | Collecting 1 |
| 954 | Collecting 2 |
| 955 | Collecting 3 |
| 956 | Done 3 |
| 957 | Collected in 741 ms |
| 958 | ``` |
| 959 | |
| 960 | <!--- TEST ARBITRARY_TIME --> |
| 961 | |
| 962 | ### Composing multiple flows |
| 963 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 964 | There are lots of ways to compose multiple flows. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 965 | |
| 966 | #### Zip |
| 967 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 968 | Just like the [Sequence.zip] extension function in the Kotlin standard library, |
| 969 | flows have a [zip] operator that combines the corresponding values of two flows: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 970 | |
| 971 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 972 | |
| 973 | ```kotlin |
| 974 | import kotlinx.coroutines.* |
| 975 | import kotlinx.coroutines.flow.* |
| 976 | |
| 977 | fun main() = runBlocking<Unit> { |
| 978 | //sampleStart |
| 979 | val nums = (1..3).asFlow() // numbers 1..3 |
| 980 | val strs = flowOf("one", "two", "three") // strings |
| 981 | nums.zip(strs) { a, b -> "$a -> $b" } // compose a single string |
| 982 | .collect { println(it) } // collect and print |
| 983 | //sampleEnd |
| 984 | } |
| 985 | ``` |
| 986 | |
| 987 | </div> |
| 988 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 989 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-20.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 990 | |
| 991 | This example prints: |
| 992 | |
| 993 | ```text |
| 994 | 1 -> one |
| 995 | 2 -> two |
| 996 | 3 -> three |
| 997 | ``` |
| 998 | |
| 999 | <!--- TEST --> |
| 1000 | |
| 1001 | #### Combine |
| 1002 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1003 | When flow represents the most recent value of a variable or operation (see also the related |
| 1004 | section on [conflation](#conflation)), it might be needed to perform a computation that depends on |
| 1005 | the most recent values of the corresponding flows and to recompute it whenever any of the upstream |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1006 | flows emit a value. The corresponding family of operators is called [combine]. |
| 1007 | |
| 1008 | For example, if the numbers in the previous example update every 300ms, but strings update every 400 ms, |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1009 | then zipping them using the [zip] operator will still produce the same result, |
| 1010 | albeit results that are printed every 400 ms: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1011 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1012 | > We use a [onEach] intermediate operator in this example to delay each element and make the code |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1013 | that emits sample flows more declarative and shorter. |
| 1014 | |
| 1015 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1016 | |
| 1017 | ```kotlin |
| 1018 | import kotlinx.coroutines.* |
| 1019 | import kotlinx.coroutines.flow.* |
| 1020 | |
| 1021 | fun main() = runBlocking<Unit> { |
| 1022 | //sampleStart |
| 1023 | val nums = (1..3).asFlow().onEach { delay(300) } // numbers 1..3 every 300 ms |
| 1024 | val strs = flowOf("one", "two", "three").onEach { delay(400) } // strings every 400 ms |
| 1025 | val startTime = System.currentTimeMillis() // remember the start time |
| 1026 | nums.zip(strs) { a, b -> "$a -> $b" } // compose a single string with "zip" |
| 1027 | .collect { value -> // collect and print |
| 1028 | println("$value at ${System.currentTimeMillis() - startTime} ms from start") |
| 1029 | } |
| 1030 | //sampleEnd |
| 1031 | } |
| 1032 | ``` |
| 1033 | |
| 1034 | </div> |
| 1035 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1036 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-21.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1037 | |
| 1038 | <!--- TEST ARBITRARY_TIME |
| 1039 | 1 -> one at 437 ms from start |
| 1040 | 2 -> two at 837 ms from start |
| 1041 | 3 -> three at 1243 ms from start |
| 1042 | --> |
| 1043 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1044 | However, when using a [combine] operator here instead of a [zip]: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1045 | |
| 1046 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1047 | |
| 1048 | ```kotlin |
| 1049 | import kotlinx.coroutines.* |
| 1050 | import kotlinx.coroutines.flow.* |
| 1051 | |
| 1052 | fun main() = runBlocking<Unit> { |
| 1053 | //sampleStart |
| 1054 | val nums = (1..3).asFlow().onEach { delay(300) } // numbers 1..3 every 300 ms |
| 1055 | val strs = flowOf("one", "two", "three").onEach { delay(400) } // strings every 400 ms |
Roman Elizarov | a73862f | 2019-09-02 17:31:14 +0300 | [diff] [blame] | 1056 | val startTime = System.currentTimeMillis() // remember the start time |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1057 | nums.combine(strs) { a, b -> "$a -> $b" } // compose a single string with "combine" |
| 1058 | .collect { value -> // collect and print |
| 1059 | println("$value at ${System.currentTimeMillis() - startTime} ms from start") |
| 1060 | } |
| 1061 | //sampleEnd |
| 1062 | } |
| 1063 | ``` |
| 1064 | |
| 1065 | </div> |
| 1066 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1067 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-22.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1068 | |
| 1069 | We get quite a different output, where a line is printed at each emission from either `nums` or `strs` flows: |
| 1070 | |
| 1071 | ```text |
| 1072 | 1 -> one at 452 ms from start |
| 1073 | 2 -> one at 651 ms from start |
| 1074 | 2 -> two at 854 ms from start |
| 1075 | 3 -> two at 952 ms from start |
| 1076 | 3 -> three at 1256 ms from start |
| 1077 | ``` |
| 1078 | |
| 1079 | <!--- TEST ARBITRARY_TIME --> |
| 1080 | |
| 1081 | ### Flattening flows |
| 1082 | |
| 1083 | Flows represent asynchronously received sequences of values, so it is quite easy to get in a situation where |
| 1084 | each value triggers a request for another sequence of values. For example, we can have the following |
| 1085 | function that returns a flow of two strings 500 ms apart: |
| 1086 | |
| 1087 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 1088 | |
| 1089 | ```kotlin |
| 1090 | fun requestFlow(i: Int): Flow<String> = flow { |
| 1091 | emit("$i: First") |
| 1092 | delay(500) // wait 500 ms |
| 1093 | emit("$i: Second") |
| 1094 | } |
| 1095 | ``` |
| 1096 | |
| 1097 | </div> |
| 1098 | |
| 1099 | <!--- CLEAR --> |
| 1100 | |
| 1101 | Now if we have a flow of three integers and call `requestFlow` for each of them like this: |
| 1102 | |
| 1103 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 1104 | |
| 1105 | ```kotlin |
| 1106 | (1..3).asFlow().map { requestFlow(it) } |
| 1107 | ``` |
| 1108 | |
| 1109 | </div> |
| 1110 | |
| 1111 | <!--- CLEAR --> |
| 1112 | |
| 1113 | Then we end up with a flow of flows (`Flow<Flow<String>>`) that needs to be _flattened_ into a single flow for |
| 1114 | further processing. Collections and sequences have [flatten][Sequence.flatten] and [flatMap][Sequence.flatMap] |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1115 | operators for this. However, due the asynchronous nature of flows they call for different _modes_ of flattening, |
| 1116 | as such, there is a family of flattening operators on flows. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1117 | |
| 1118 | #### flatMapConcat |
| 1119 | |
| 1120 | Concatenating mode is implemented by [flatMapConcat] and [flattenConcat] operators. They are the most direct |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1121 | analogues of the corresponding sequence operators. They wait for the inner flow to complete before |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1122 | starting to collect the next one as the following example shows: |
| 1123 | |
| 1124 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1125 | |
| 1126 | ```kotlin |
| 1127 | import kotlinx.coroutines.* |
| 1128 | import kotlinx.coroutines.flow.* |
| 1129 | |
| 1130 | fun requestFlow(i: Int): Flow<String> = flow { |
| 1131 | emit("$i: First") |
| 1132 | delay(500) // wait 500 ms |
| 1133 | emit("$i: Second") |
| 1134 | } |
| 1135 | |
| 1136 | fun main() = runBlocking<Unit> { |
| 1137 | //sampleStart |
Roman Elizarov | a73862f | 2019-09-02 17:31:14 +0300 | [diff] [blame] | 1138 | val startTime = System.currentTimeMillis() // remember the start time |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1139 | (1..3).asFlow().onEach { delay(100) } // a number every 100 ms |
| 1140 | .flatMapConcat { requestFlow(it) } |
| 1141 | .collect { value -> // collect and print |
| 1142 | println("$value at ${System.currentTimeMillis() - startTime} ms from start") |
| 1143 | } |
| 1144 | //sampleEnd |
| 1145 | } |
| 1146 | ``` |
| 1147 | |
| 1148 | </div> |
| 1149 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1150 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-23.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1151 | |
| 1152 | The sequential nature of [flatMapConcat] is clearly seen in the output: |
| 1153 | |
| 1154 | ```text |
| 1155 | 1: First at 121 ms from start |
| 1156 | 1: Second at 622 ms from start |
| 1157 | 2: First at 727 ms from start |
| 1158 | 2: Second at 1227 ms from start |
| 1159 | 3: First at 1328 ms from start |
| 1160 | 3: Second at 1829 ms from start |
| 1161 | ``` |
| 1162 | |
| 1163 | <!--- TEST ARBITRARY_TIME --> |
| 1164 | |
| 1165 | #### flatMapMerge |
| 1166 | |
| 1167 | Another flattening mode is to concurrently collect all the incoming flows and merge their values into |
| 1168 | a single flow so that values are emitted as soon as possible. |
| 1169 | It is implemented by [flatMapMerge] and [flattenMerge] operators. They both accept an optional |
| 1170 | `concurrency` parameter that limits the number of concurrent flows that are collected at the same time |
| 1171 | (it is equal to [DEFAULT_CONCURRENCY] by default). |
| 1172 | |
| 1173 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1174 | |
| 1175 | ```kotlin |
| 1176 | import kotlinx.coroutines.* |
| 1177 | import kotlinx.coroutines.flow.* |
| 1178 | |
| 1179 | fun requestFlow(i: Int): Flow<String> = flow { |
| 1180 | emit("$i: First") |
| 1181 | delay(500) // wait 500 ms |
| 1182 | emit("$i: Second") |
| 1183 | } |
| 1184 | |
| 1185 | fun main() = runBlocking<Unit> { |
| 1186 | //sampleStart |
Roman Elizarov | a73862f | 2019-09-02 17:31:14 +0300 | [diff] [blame] | 1187 | val startTime = System.currentTimeMillis() // remember the start time |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1188 | (1..3).asFlow().onEach { delay(100) } // a number every 100 ms |
| 1189 | .flatMapMerge { requestFlow(it) } |
| 1190 | .collect { value -> // collect and print |
| 1191 | println("$value at ${System.currentTimeMillis() - startTime} ms from start") |
| 1192 | } |
| 1193 | //sampleEnd |
| 1194 | } |
| 1195 | ``` |
| 1196 | |
| 1197 | </div> |
| 1198 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1199 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-24.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1200 | |
| 1201 | The concurrent nature of [flatMapMerge] is obvious: |
| 1202 | |
| 1203 | ```text |
| 1204 | 1: First at 136 ms from start |
| 1205 | 2: First at 231 ms from start |
| 1206 | 3: First at 333 ms from start |
| 1207 | 1: Second at 639 ms from start |
| 1208 | 2: Second at 732 ms from start |
| 1209 | 3: Second at 833 ms from start |
| 1210 | ``` |
| 1211 | |
| 1212 | <!--- TEST ARBITRARY_TIME --> |
| 1213 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1214 | > Note that the [flatMapMerge] calls its block of code (`{ requestFlow(it) }` in this example) sequentially, but |
| 1215 | collects the resulting flows concurrently, it is the equivalent of performing a sequential |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1216 | `map { requestFlow(it) }` first and then calling [flattenMerge] on the result. |
| 1217 | |
| 1218 | #### flatMapLatest |
| 1219 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1220 | In a similar way to the [collectLatest] operator, that was shown in |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1221 | ["Processing the latest value"](#processing-the-latest-value) section, there is the corresponding "Latest" |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1222 | flattening mode where a collection of the previous flow is cancelled as soon as new flow is emitted. |
| 1223 | It is implemented by the [flatMapLatest] operator. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1224 | |
| 1225 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1226 | |
| 1227 | ```kotlin |
| 1228 | import kotlinx.coroutines.* |
| 1229 | import kotlinx.coroutines.flow.* |
| 1230 | |
| 1231 | fun requestFlow(i: Int): Flow<String> = flow { |
| 1232 | emit("$i: First") |
| 1233 | delay(500) // wait 500 ms |
| 1234 | emit("$i: Second") |
| 1235 | } |
| 1236 | |
| 1237 | fun main() = runBlocking<Unit> { |
| 1238 | //sampleStart |
Roman Elizarov | a73862f | 2019-09-02 17:31:14 +0300 | [diff] [blame] | 1239 | val startTime = System.currentTimeMillis() // remember the start time |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1240 | (1..3).asFlow().onEach { delay(100) } // a number every 100 ms |
| 1241 | .flatMapLatest { requestFlow(it) } |
| 1242 | .collect { value -> // collect and print |
| 1243 | println("$value at ${System.currentTimeMillis() - startTime} ms from start") |
| 1244 | } |
| 1245 | //sampleEnd |
| 1246 | } |
| 1247 | ``` |
| 1248 | |
| 1249 | </div> |
| 1250 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1251 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-25.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1252 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1253 | The output here in this example is a good demonstration of how [flatMapLatest] works: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1254 | |
| 1255 | ```text |
| 1256 | 1: First at 142 ms from start |
| 1257 | 2: First at 322 ms from start |
| 1258 | 3: First at 425 ms from start |
| 1259 | 3: Second at 931 ms from start |
| 1260 | ``` |
| 1261 | |
| 1262 | <!--- TEST ARBITRARY_TIME --> |
| 1263 | |
| 1264 | > Note that [flatMapLatest] cancels all the code in its block (`{ requestFlow(it) }` in this example) on a new value. |
| 1265 | It makes no difference in this particular example, because the call to `requestFlow` itself is fast, not-suspending, |
| 1266 | and cannot be cancelled. However, it would show up if we were to use suspending functions like `delay` in there. |
| 1267 | |
| 1268 | ### Flow exceptions |
| 1269 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1270 | Flow collection can complete with an exception when an emitter or code inside the operators throw an exception. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1271 | There are several ways to handle these exceptions. |
| 1272 | |
| 1273 | #### Collector try and catch |
| 1274 | |
| 1275 | A collector can use Kotlin's [`try/catch`][exceptions] block to handle exceptions: |
| 1276 | |
| 1277 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1278 | |
| 1279 | ```kotlin |
| 1280 | import kotlinx.coroutines.* |
| 1281 | import kotlinx.coroutines.flow.* |
| 1282 | |
| 1283 | //sampleStart |
| 1284 | fun foo(): Flow<Int> = flow { |
| 1285 | for (i in 1..3) { |
| 1286 | println("Emitting $i") |
| 1287 | emit(i) // emit next value |
| 1288 | } |
| 1289 | } |
| 1290 | |
| 1291 | fun main() = runBlocking<Unit> { |
| 1292 | try { |
| 1293 | foo().collect { value -> |
| 1294 | println(value) |
| 1295 | check(value <= 1) { "Collected $value" } |
| 1296 | } |
| 1297 | } catch (e: Throwable) { |
| 1298 | println("Caught $e") |
| 1299 | } |
| 1300 | } |
| 1301 | //sampleEnd |
| 1302 | ``` |
| 1303 | |
| 1304 | </div> |
| 1305 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1306 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-26.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1307 | |
| 1308 | This code successfully catches an exception in [collect] terminal operator and, |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1309 | as we see, no more values are emitted after that: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1310 | |
| 1311 | ```text |
| 1312 | Emitting 1 |
| 1313 | 1 |
| 1314 | Emitting 2 |
| 1315 | 2 |
| 1316 | Caught java.lang.IllegalStateException: Collected 2 |
| 1317 | ``` |
| 1318 | |
| 1319 | <!--- TEST --> |
| 1320 | |
| 1321 | #### Everything is caught |
| 1322 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1323 | The previous example actually catches any exception happening in the emitter or in any intermediate or terminal operators. |
| 1324 | For example, let's change the code so that emitted values are [mapped][map] to strings, |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1325 | but the corresponding code produces an exception: |
| 1326 | |
| 1327 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1328 | |
| 1329 | ```kotlin |
| 1330 | import kotlinx.coroutines.* |
| 1331 | import kotlinx.coroutines.flow.* |
| 1332 | |
| 1333 | //sampleStart |
| 1334 | fun foo(): Flow<String> = |
| 1335 | flow { |
| 1336 | for (i in 1..3) { |
| 1337 | println("Emitting $i") |
| 1338 | emit(i) // emit next value |
| 1339 | } |
| 1340 | } |
| 1341 | .map { value -> |
| 1342 | check(value <= 1) { "Crashed on $value" } |
| 1343 | "string $value" |
| 1344 | } |
| 1345 | |
| 1346 | fun main() = runBlocking<Unit> { |
| 1347 | try { |
| 1348 | foo().collect { value -> println(value) } |
| 1349 | } catch (e: Throwable) { |
| 1350 | println("Caught $e") |
| 1351 | } |
| 1352 | } |
| 1353 | //sampleEnd |
| 1354 | ``` |
| 1355 | |
| 1356 | </div> |
| 1357 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1358 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-27.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1359 | |
| 1360 | This exception is still caught and collection is stopped: |
| 1361 | |
| 1362 | ```text |
| 1363 | Emitting 1 |
| 1364 | string 1 |
| 1365 | Emitting 2 |
| 1366 | Caught java.lang.IllegalStateException: Crashed on 2 |
| 1367 | ``` |
| 1368 | |
| 1369 | <!--- TEST --> |
| 1370 | |
| 1371 | ### Exception transparency |
| 1372 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1373 | But how can code of the emitter encapsulate its exception handling behavior? |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1374 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1375 | Flows must be _transparent to exceptions_ and it is a violation of the exception transparency to [emit][FlowCollector.emit] values in the |
| 1376 | `flow { ... }` builder from inside of a `try/catch` block. This guarantees that a collector throwing an exception |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1377 | can always catch it using `try/catch` as in the previous example. |
| 1378 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1379 | The emitter can use a [catch] operator that preserves this exception transparency and allows encapsulation |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1380 | of its exception handling. The body of the `catch` operator can analyze an exception |
| 1381 | and react to it in different ways depending on which exception was caught: |
| 1382 | |
| 1383 | * Exceptions can be rethrown using `throw`. |
| 1384 | * Exceptions can be turned into emission of values using [emit][FlowCollector.emit] from the body of [catch]. |
| 1385 | * Exceptions can be ignored, logged, or processed by some other code. |
| 1386 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1387 | For example, let us emit the text on catching an exception: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1388 | |
| 1389 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1390 | |
| 1391 | ```kotlin |
| 1392 | import kotlinx.coroutines.* |
| 1393 | import kotlinx.coroutines.flow.* |
| 1394 | |
| 1395 | fun foo(): Flow<String> = |
| 1396 | flow { |
| 1397 | for (i in 1..3) { |
| 1398 | println("Emitting $i") |
| 1399 | emit(i) // emit next value |
| 1400 | } |
| 1401 | } |
| 1402 | .map { value -> |
| 1403 | check(value <= 1) { "Crashed on $value" } |
| 1404 | "string $value" |
| 1405 | } |
| 1406 | |
| 1407 | fun main() = runBlocking<Unit> { |
| 1408 | //sampleStart |
| 1409 | foo() |
| 1410 | .catch { e -> emit("Caught $e") } // emit on exception |
| 1411 | .collect { value -> println(value) } |
| 1412 | //sampleEnd |
| 1413 | } |
| 1414 | ``` |
| 1415 | |
| 1416 | </div> |
| 1417 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1418 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-28.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1419 | |
| 1420 | The output of the example is the same, even though we do not have `try/catch` around the code anymore. |
| 1421 | |
| 1422 | <!--- TEST |
| 1423 | Emitting 1 |
| 1424 | string 1 |
| 1425 | Emitting 2 |
| 1426 | Caught java.lang.IllegalStateException: Crashed on 2 |
| 1427 | --> |
| 1428 | |
| 1429 | #### Transparent catch |
| 1430 | |
| 1431 | The [catch] intermediate operator, honoring exception transparency, catches only upstream exceptions |
| 1432 | (that is an exception from all the operators above `catch`, but not below it). |
| 1433 | If the block in `collect { ... }` (placed below `catch`) throws an exception then it escapes: |
| 1434 | |
| 1435 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1436 | |
| 1437 | ```kotlin |
| 1438 | import kotlinx.coroutines.* |
| 1439 | import kotlinx.coroutines.flow.* |
| 1440 | |
| 1441 | //sampleStart |
| 1442 | fun foo(): Flow<Int> = flow { |
| 1443 | for (i in 1..3) { |
| 1444 | println("Emitting $i") |
| 1445 | emit(i) |
| 1446 | } |
| 1447 | } |
| 1448 | |
| 1449 | fun main() = runBlocking<Unit> { |
| 1450 | foo() |
| 1451 | .catch { e -> println("Caught $e") } // does not catch downstream exceptions |
| 1452 | .collect { value -> |
| 1453 | check(value <= 1) { "Collected $value" } |
| 1454 | println(value) |
| 1455 | } |
| 1456 | } |
| 1457 | //sampleEnd |
| 1458 | ``` |
| 1459 | |
| 1460 | </div> |
| 1461 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1462 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-29.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1463 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1464 | A "Caught ..." message is not printed despite there being a `catch` operator: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1465 | |
| 1466 | <!--- TEST EXCEPTION |
| 1467 | Emitting 1 |
| 1468 | 1 |
| 1469 | Emitting 2 |
| 1470 | Exception in thread "main" java.lang.IllegalStateException: Collected 2 |
| 1471 | at ... |
| 1472 | --> |
| 1473 | |
| 1474 | #### Catching declaratively |
| 1475 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1476 | We can combine the declarative nature of the [catch] operator with a desire to handle all the exceptions, by moving the body |
| 1477 | of the [collect] operator into [onEach] and putting it before the `catch` operator. Collection of this flow must |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1478 | be triggered by a call to `collect()` without parameters: |
| 1479 | |
| 1480 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1481 | |
| 1482 | ```kotlin |
| 1483 | import kotlinx.coroutines.* |
| 1484 | import kotlinx.coroutines.flow.* |
| 1485 | |
| 1486 | fun foo(): Flow<Int> = flow { |
| 1487 | for (i in 1..3) { |
| 1488 | println("Emitting $i") |
| 1489 | emit(i) |
| 1490 | } |
| 1491 | } |
| 1492 | |
| 1493 | fun main() = runBlocking<Unit> { |
| 1494 | //sampleStart |
| 1495 | foo() |
| 1496 | .onEach { value -> |
| 1497 | check(value <= 1) { "Collected $value" } |
| 1498 | println(value) |
| 1499 | } |
| 1500 | .catch { e -> println("Caught $e") } |
| 1501 | .collect() |
| 1502 | //sampleEnd |
| 1503 | } |
| 1504 | ``` |
| 1505 | |
| 1506 | </div> |
| 1507 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1508 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-30.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1509 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1510 | Now we can see that a "Caught ..." message is printed and so we can catch all the exceptions without explicitly |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1511 | using a `try/catch` block: |
| 1512 | |
| 1513 | <!--- TEST EXCEPTION |
| 1514 | Emitting 1 |
| 1515 | 1 |
| 1516 | Emitting 2 |
| 1517 | Caught java.lang.IllegalStateException: Collected 2 |
| 1518 | --> |
| 1519 | |
| 1520 | ### Flow completion |
| 1521 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1522 | When flow collection completes (normally or exceptionally) it may need to execute an action. |
| 1523 | As you may have already noticed, it can be done in two ways: imperative or declarative. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1524 | |
| 1525 | #### Imperative finally block |
| 1526 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1527 | In addition to `try`/`catch`, a collector can also use a `finally` block to execute an action |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1528 | upon `collect` completion. |
| 1529 | |
| 1530 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1531 | |
| 1532 | ```kotlin |
| 1533 | import kotlinx.coroutines.* |
| 1534 | import kotlinx.coroutines.flow.* |
| 1535 | |
| 1536 | //sampleStart |
| 1537 | fun foo(): Flow<Int> = (1..3).asFlow() |
| 1538 | |
| 1539 | fun main() = runBlocking<Unit> { |
| 1540 | try { |
| 1541 | foo().collect { value -> println(value) } |
| 1542 | } finally { |
| 1543 | println("Done") |
| 1544 | } |
| 1545 | } |
| 1546 | //sampleEnd |
| 1547 | ``` |
| 1548 | |
| 1549 | </div> |
| 1550 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1551 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-31.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1552 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1553 | This code prints three numbers produced by the `foo()` flow followed by a "Done" string: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1554 | |
| 1555 | ```text |
| 1556 | 1 |
| 1557 | 2 |
| 1558 | 3 |
| 1559 | Done |
| 1560 | ``` |
| 1561 | |
| 1562 | <!--- TEST --> |
| 1563 | |
| 1564 | #### Declarative handling |
| 1565 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1566 | For the declarative approach, flow has [onCompletion] intermediate operator that is invoked |
| 1567 | when the flow has completely collected. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1568 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1569 | The previous example can be rewritten using an [onCompletion] operator and produces the same output: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1570 | |
| 1571 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1572 | |
| 1573 | ```kotlin |
| 1574 | import kotlinx.coroutines.* |
| 1575 | import kotlinx.coroutines.flow.* |
| 1576 | |
| 1577 | fun foo(): Flow<Int> = (1..3).asFlow() |
| 1578 | |
| 1579 | fun main() = runBlocking<Unit> { |
| 1580 | //sampleStart |
| 1581 | foo() |
| 1582 | .onCompletion { println("Done") } |
| 1583 | .collect { value -> println(value) } |
| 1584 | //sampleEnd |
| 1585 | } |
| 1586 | ``` |
| 1587 | </div> |
| 1588 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1589 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-32.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1590 | |
| 1591 | <!--- TEST |
| 1592 | 1 |
| 1593 | 2 |
| 1594 | 3 |
| 1595 | Done |
| 1596 | --> |
| 1597 | |
| 1598 | The key advantage of [onCompletion] is a nullable `Throwable` parameter of the lambda that can be used |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1599 | to determine whether the flow collection was completed normally or exceptionally. In the following |
| 1600 | example the `foo()` flow throws an exception after emitting the number 1: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1601 | |
| 1602 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1603 | |
| 1604 | ```kotlin |
| 1605 | import kotlinx.coroutines.* |
| 1606 | import kotlinx.coroutines.flow.* |
| 1607 | |
| 1608 | //sampleStart |
| 1609 | fun foo(): Flow<Int> = flow { |
| 1610 | emit(1) |
| 1611 | throw RuntimeException() |
| 1612 | } |
| 1613 | |
| 1614 | fun main() = runBlocking<Unit> { |
| 1615 | foo() |
| 1616 | .onCompletion { cause -> if (cause != null) println("Flow completed exceptionally") } |
| 1617 | .catch { cause -> println("Caught exception") } |
| 1618 | .collect { value -> println(value) } |
| 1619 | } |
| 1620 | //sampleEnd |
| 1621 | ``` |
| 1622 | </div> |
| 1623 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1624 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-33.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1625 | |
| 1626 | As you may expect, it prints: |
| 1627 | |
| 1628 | ```text |
| 1629 | 1 |
| 1630 | Flow completed exceptionally |
| 1631 | Caught exception |
| 1632 | ``` |
| 1633 | |
| 1634 | <!--- TEST --> |
| 1635 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1636 | The [onCompletion] operator, unlike [catch], does not handle the exception. As we can see from the above |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1637 | example code, the exception still flows downstream. It will be delivered to further `onCompletion` operators |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1638 | and can be handled with a `catch` operator. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1639 | |
Roman Elizarov | eb4e7d3 | 2020-04-27 15:04:00 +0300 | [diff] [blame] | 1640 | #### Successful completion |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1641 | |
Roman Elizarov | eb4e7d3 | 2020-04-27 15:04:00 +0300 | [diff] [blame] | 1642 | Another difference with [catch] operator is that [onCompletion] sees all exceptions and receives |
| 1643 | a `null` exception only on successful completion of the upstream flow (without cancellation or failure). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1644 | |
| 1645 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1646 | |
| 1647 | ```kotlin |
| 1648 | import kotlinx.coroutines.* |
| 1649 | import kotlinx.coroutines.flow.* |
| 1650 | |
| 1651 | //sampleStart |
| 1652 | fun foo(): Flow<Int> = (1..3).asFlow() |
| 1653 | |
| 1654 | fun main() = runBlocking<Unit> { |
| 1655 | foo() |
| 1656 | .onCompletion { cause -> println("Flow completed with $cause") } |
| 1657 | .collect { value -> |
| 1658 | check(value <= 1) { "Collected $value" } |
| 1659 | println(value) |
| 1660 | } |
| 1661 | } |
| 1662 | //sampleEnd |
| 1663 | ``` |
| 1664 | |
| 1665 | </div> |
| 1666 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1667 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-34.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1668 | |
Roman Elizarov | eb4e7d3 | 2020-04-27 15:04:00 +0300 | [diff] [blame] | 1669 | We can see the completion cause is not null, because the flow was aborted due to downstream exception: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1670 | |
| 1671 | ```text |
| 1672 | 1 |
Roman Elizarov | eb4e7d3 | 2020-04-27 15:04:00 +0300 | [diff] [blame] | 1673 | Flow completed with java.lang.IllegalStateException: Collected 2 |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1674 | Exception in thread "main" java.lang.IllegalStateException: Collected 2 |
| 1675 | ``` |
| 1676 | |
| 1677 | <!--- TEST EXCEPTION --> |
| 1678 | |
| 1679 | ### Imperative versus declarative |
| 1680 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1681 | Now we know how to collect flow, and handle its completion and exceptions in both imperative and declarative ways. |
| 1682 | The natural question here is, which approach is preferred and why? |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1683 | As a library, we do not advocate for any particular approach and believe that both options |
| 1684 | are valid and should be selected according to your own preferences and code style. |
| 1685 | |
| 1686 | ### Launching flow |
| 1687 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1688 | It is easy to use flows to represent asynchronous events that are coming from some source. |
| 1689 | In this case, we need an analogue of the `addEventListener` function that registers a piece of code with a reaction |
| 1690 | for incoming events and continues further work. The [onEach] operator can serve this role. |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1691 | However, `onEach` is an intermediate operator. We also need a terminal operator to collect the flow. |
| 1692 | Otherwise, just calling `onEach` has no effect. |
| 1693 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1694 | If we use the [collect] terminal operator after `onEach`, then the code after it will wait until the flow is collected: |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1695 | |
| 1696 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1697 | |
| 1698 | ```kotlin |
| 1699 | import kotlinx.coroutines.* |
| 1700 | import kotlinx.coroutines.flow.* |
| 1701 | |
| 1702 | //sampleStart |
| 1703 | // Imitate a flow of events |
| 1704 | fun events(): Flow<Int> = (1..3).asFlow().onEach { delay(100) } |
| 1705 | |
| 1706 | fun main() = runBlocking<Unit> { |
| 1707 | events() |
| 1708 | .onEach { event -> println("Event: $event") } |
| 1709 | .collect() // <--- Collecting the flow waits |
| 1710 | println("Done") |
| 1711 | } |
| 1712 | //sampleEnd |
| 1713 | ``` |
| 1714 | |
| 1715 | </div> |
| 1716 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1717 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-35.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1718 | |
| 1719 | As you can see, it prints: |
| 1720 | |
| 1721 | ```text |
| 1722 | Event: 1 |
| 1723 | Event: 2 |
| 1724 | Event: 3 |
| 1725 | Done |
| 1726 | ``` |
| 1727 | |
| 1728 | <!--- TEST --> |
| 1729 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1730 | The [launchIn] terminal operator comes in handy here. By replacing `collect` with `launchIn` we can |
| 1731 | launch a collection of the flow in a separate coroutine, so that execution of further code |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1732 | immediately continues: |
| 1733 | |
| 1734 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1735 | |
| 1736 | ```kotlin |
| 1737 | import kotlinx.coroutines.* |
| 1738 | import kotlinx.coroutines.flow.* |
| 1739 | |
| 1740 | // Imitate a flow of events |
| 1741 | fun events(): Flow<Int> = (1..3).asFlow().onEach { delay(100) } |
| 1742 | |
| 1743 | //sampleStart |
| 1744 | fun main() = runBlocking<Unit> { |
| 1745 | events() |
| 1746 | .onEach { event -> println("Event: $event") } |
| 1747 | .launchIn(this) // <--- Launching the flow in a separate coroutine |
| 1748 | println("Done") |
| 1749 | } |
| 1750 | //sampleEnd |
| 1751 | ``` |
| 1752 | |
| 1753 | </div> |
| 1754 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1755 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-36.kt). |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1756 | |
| 1757 | It prints: |
| 1758 | |
| 1759 | ```text |
| 1760 | Done |
| 1761 | Event: 1 |
| 1762 | Event: 2 |
| 1763 | Event: 3 |
| 1764 | ``` |
| 1765 | |
| 1766 | <!--- TEST --> |
| 1767 | |
| 1768 | The required parameter to `launchIn` must specify a [CoroutineScope] in which the coroutine to collect the flow is |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1769 | launched. In the above example this scope comes from the [runBlocking] |
| 1770 | coroutine builder, so while the flow is running, this [runBlocking] scope waits for completion of its child coroutine |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1771 | and keeps the main function from returning and terminating this example. |
| 1772 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1773 | In actual applications a scope will come from an entity with a limited |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1774 | lifetime. As soon as the lifetime of this entity is terminated the corresponding scope is cancelled, cancelling |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1775 | the collection of the corresponding flow. This way the pair of `onEach { ... }.launchIn(scope)` works |
| 1776 | like the `addEventListener`. However, there is no need for the corresponding `removeEventListener` function, |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1777 | as cancellation and structured concurrency serve this purpose. |
| 1778 | |
David.Watson | bb714c5 | 2019-08-30 17:49:42 +0200 | [diff] [blame] | 1779 | Note that [launchIn] also returns a [Job], which can be used to [cancel][Job.cancel] the corresponding flow collection |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1780 | coroutine only without cancelling the whole scope or to [join][Job.join] it. |
| 1781 | |
Roman Elizarov | 9bbb669 | 2020-06-03 12:02:17 +0300 | [diff] [blame^] | 1782 | ### Flow cancellation checks |
| 1783 | |
| 1784 | For convenience, the [flow] builder performs additional [ensureActive] checks for cancellation on each emitted value. |
| 1785 | It means that a busy loop emitting from a `flow { ... }` is cancellable: |
| 1786 | |
| 1787 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1788 | |
| 1789 | ```kotlin |
| 1790 | import kotlinx.coroutines.* |
| 1791 | import kotlinx.coroutines.flow.* |
| 1792 | |
| 1793 | //sampleStart |
| 1794 | fun foo(): Flow<Int> = flow { |
| 1795 | for (i in 1..5) { |
| 1796 | println("Emitting $i") |
| 1797 | emit(i) |
| 1798 | } |
| 1799 | } |
| 1800 | |
| 1801 | fun main() = runBlocking<Unit> { |
| 1802 | foo().collect { value -> |
| 1803 | if (value == 3) cancel() |
| 1804 | println(value) |
| 1805 | } |
| 1806 | } |
| 1807 | //sampleEnd |
| 1808 | ``` |
| 1809 | |
| 1810 | </div> |
| 1811 | |
| 1812 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-37.kt). |
| 1813 | |
| 1814 | We get only numbers up to 3 and a [CancellationException] after trying to emit number 4: |
| 1815 | |
| 1816 | ```text |
| 1817 | Emitting 1 |
| 1818 | 1 |
| 1819 | Emitting 2 |
| 1820 | 2 |
| 1821 | Emitting 3 |
| 1822 | 3 |
| 1823 | Emitting 4 |
| 1824 | Exception in thread "main" kotlinx.coroutines.JobCancellationException: BlockingCoroutine was cancelled; job="coroutine#1":BlockingCoroutine{Cancelled}@6d7b4f4c |
| 1825 | ``` |
| 1826 | |
| 1827 | <!--- TEST EXCEPTION --> |
| 1828 | |
| 1829 | However, most other flow operators do not do additional cancellation checks on their own for performance reasons. |
| 1830 | For example, if you use [IntRange.asFlow] extension to write the same busy loop and don't suspend anywhere, |
| 1831 | then there are no checks for cancellation: |
| 1832 | |
| 1833 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1834 | |
| 1835 | ```kotlin |
| 1836 | import kotlinx.coroutines.* |
| 1837 | import kotlinx.coroutines.flow.* |
| 1838 | |
| 1839 | //sampleStart |
| 1840 | fun main() = runBlocking<Unit> { |
| 1841 | (1..5).asFlow().collect { value -> |
| 1842 | if (value == 3) cancel() |
| 1843 | println(value) |
| 1844 | } |
| 1845 | } |
| 1846 | //sampleEnd |
| 1847 | ``` |
| 1848 | |
| 1849 | </div> |
| 1850 | |
| 1851 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-38.kt). |
| 1852 | |
| 1853 | All numbers from 1 to 5 are collected and cancellation gets detected only before return from `runBlocking`: |
| 1854 | |
| 1855 | ```text |
| 1856 | 1 |
| 1857 | 2 |
| 1858 | 3 |
| 1859 | 4 |
| 1860 | 5 |
| 1861 | Exception in thread "main" kotlinx.coroutines.JobCancellationException: BlockingCoroutine was cancelled; job="coroutine#1":BlockingCoroutine{Cancelled}@3327bd23 |
| 1862 | ``` |
| 1863 | |
| 1864 | <!--- TEST EXCEPTION --> |
| 1865 | |
| 1866 | #### Making busy flow cancellable |
| 1867 | |
| 1868 | In the case where you have a busy loop with coroutines you must explicitly check for cancellation. |
| 1869 | You can add `.onEach { currentCoroutineContext().ensureActive() }`, but there is a ready-to-use |
| 1870 | [cancellable] operator provided to do that: |
| 1871 | |
| 1872 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
| 1873 | |
| 1874 | ```kotlin |
| 1875 | import kotlinx.coroutines.* |
| 1876 | import kotlinx.coroutines.flow.* |
| 1877 | |
| 1878 | //sampleStart |
| 1879 | fun main() = runBlocking<Unit> { |
| 1880 | (1..5).asFlow().cancellable().collect { value -> |
| 1881 | if (value == 3) cancel() |
| 1882 | println(value) |
| 1883 | } |
| 1884 | } |
| 1885 | //sampleEnd |
| 1886 | ``` |
| 1887 | |
| 1888 | </div> |
| 1889 | |
| 1890 | > You can get the full code from [here](../kotlinx-coroutines-core/jvm/test/guide/example-flow-39.kt). |
| 1891 | |
| 1892 | With the `cancellable` operator only the numbers from 1 to 3 are collected: |
| 1893 | |
| 1894 | ```text |
| 1895 | 1 |
| 1896 | 2 |
| 1897 | 3 |
| 1898 | Exception in thread "main" kotlinx.coroutines.JobCancellationException: BlockingCoroutine was cancelled; job="coroutine#1":BlockingCoroutine{Cancelled}@5ec0a365 |
| 1899 | ``` |
| 1900 | |
| 1901 | <!--- TEST EXCEPTION --> |
| 1902 | |
Vsevolod Tolstopyatov | c99704a | 2019-09-24 19:30:49 +0300 | [diff] [blame] | 1903 | ### Flow and Reactive Streams |
| 1904 | |
| 1905 | For those who are familiar with [Reactive Streams](https://www.reactive-streams.org/) or reactive frameworks such as RxJava and project Reactor, |
| 1906 | design of the Flow may look very familiar. |
| 1907 | |
| 1908 | Indeed, its design was inspired by Reactive Streams and its various implementations. But Flow main goal is to have as simple design as possible, |
| 1909 | be Kotlin and suspension friendly and respect structured concurrency. Achieving this goal would be impossible without reactive pioneers and their tremendous work. You can read the complete story in [Reactive Streams and Kotlin Flows](https://medium.com/@elizarov/reactive-streams-and-kotlin-flows-bfd12772cda4) article. |
| 1910 | |
| 1911 | 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. |
Vsevolod Tolstopyatov | 3250e47 | 2020-04-24 19:32:55 +0300 | [diff] [blame] | 1912 | 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). |
Vsevolod Tolstopyatov | c99704a | 2019-09-24 19:30:49 +0300 | [diff] [blame] | 1913 | Integration modules include conversions from and to `Flow`, integration with Reactor's `Context` and suspension-friendly ways to work with various reactive entities. |
| 1914 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1915 | <!-- stdlib references --> |
| 1916 | |
| 1917 | [collections]: https://kotlinlang.org/docs/reference/collections-overview.html |
| 1918 | [List]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html |
| 1919 | [forEach]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/for-each.html |
| 1920 | [Sequence]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/index.html |
| 1921 | [Sequence.zip]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/zip.html |
| 1922 | [Sequence.flatten]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/flatten.html |
| 1923 | [Sequence.flatMap]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/flat-map.html |
| 1924 | [exceptions]: https://kotlinlang.org/docs/reference/exceptions.html |
| 1925 | |
| 1926 | <!--- MODULE kotlinx-coroutines-core --> |
| 1927 | <!--- INDEX kotlinx.coroutines --> |
| 1928 | [delay]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/delay.html |
| 1929 | [withTimeoutOrNull]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-timeout-or-null.html |
| 1930 | [Dispatchers.Default]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html |
| 1931 | [Dispatchers.Main]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-main.html |
| 1932 | [withContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html |
| 1933 | [CoroutineDispatcher]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-dispatcher/index.html |
| 1934 | [CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html |
| 1935 | [runBlocking]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html |
| 1936 | [Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html |
| 1937 | [Job.cancel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/cancel.html |
| 1938 | [Job.join]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/join.html |
Roman Elizarov | 9bbb669 | 2020-06-03 12:02:17 +0300 | [diff] [blame^] | 1939 | [ensureActive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/ensure-active.html |
| 1940 | [CancellationException]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-cancellation-exception/index.html |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1941 | <!--- INDEX kotlinx.coroutines.flow --> |
| 1942 | [Flow]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html |
| 1943 | [flow]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow.html |
| 1944 | [FlowCollector.emit]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow-collector/emit.html |
| 1945 | [collect]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/collect.html |
| 1946 | [flowOf]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow-of.html |
| 1947 | [map]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/map.html |
| 1948 | [filter]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/filter.html |
| 1949 | [transform]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/transform.html |
| 1950 | [take]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/take.html |
| 1951 | [toList]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/to-list.html |
| 1952 | [toSet]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/to-set.html |
| 1953 | [first]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/first.html |
| 1954 | [single]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/single.html |
| 1955 | [reduce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/reduce.html |
| 1956 | [fold]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/fold.html |
| 1957 | [flowOn]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow-on.html |
| 1958 | [buffer]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/buffer.html |
| 1959 | [conflate]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/conflate.html |
| 1960 | [collectLatest]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/collect-latest.html |
| 1961 | [zip]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/zip.html |
| 1962 | [combine]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/combine.html |
| 1963 | [onEach]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/on-each.html |
| 1964 | [flatMapConcat]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flat-map-concat.html |
| 1965 | [flattenConcat]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flatten-concat.html |
| 1966 | [flatMapMerge]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flat-map-merge.html |
| 1967 | [flattenMerge]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flatten-merge.html |
| 1968 | [DEFAULT_CONCURRENCY]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-d-e-f-a-u-l-t_-c-o-n-c-u-r-r-e-n-c-y.html |
| 1969 | [flatMapLatest]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flat-map-latest.html |
| 1970 | [catch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/catch.html |
| 1971 | [onCompletion]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/on-completion.html |
| 1972 | [launchIn]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/launch-in.html |
Roman Elizarov | 9bbb669 | 2020-06-03 12:02:17 +0300 | [diff] [blame^] | 1973 | [IntRange.asFlow]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/kotlin.ranges.-int-range/as-flow.html |
| 1974 | [cancellable]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/cancellable.html |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 1975 | <!--- END --> |