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