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