Roman Elizarov | 660c2d7 | 2020-02-14 13:18:37 +0300 | [diff] [blame] | 1 | <!--- TEST_NAME ComposingGuideTest --> |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 2 | |
Prendota | b8a559d | 2018-11-30 16:24:23 +0300 | [diff] [blame] | 3 | **Table of contents** |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 4 | |
| 5 | <!--- TOC --> |
| 6 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 7 | * [Composing Suspending Functions](#composing-suspending-functions) |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 8 | * [Sequential by default](#sequential-by-default) |
| 9 | * [Concurrent using async](#concurrent-using-async) |
| 10 | * [Lazily started async](#lazily-started-async) |
| 11 | * [Async-style functions](#async-style-functions) |
| 12 | * [Structured concurrency with async](#structured-concurrency-with-async) |
| 13 | |
Roman Elizarov | 660c2d7 | 2020-02-14 13:18:37 +0300 | [diff] [blame] | 14 | <!--- END --> |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 15 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 16 | ## Composing Suspending Functions |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 17 | |
| 18 | This section covers various approaches to composition of suspending functions. |
| 19 | |
| 20 | ### Sequential by default |
| 21 | |
| 22 | Assume that we have two suspending functions defined elsewhere that do something useful like some kind of |
| 23 | remote service call or computation. We just pretend they are useful, but actually each one just |
| 24 | delays for a second for the purpose of this example: |
| 25 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 26 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 27 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 28 | ```kotlin |
| 29 | suspend fun doSomethingUsefulOne(): Int { |
| 30 | delay(1000L) // pretend we are doing something useful here |
| 31 | return 13 |
| 32 | } |
| 33 | |
| 34 | suspend fun doSomethingUsefulTwo(): Int { |
| 35 | delay(1000L) // pretend we are doing something useful here, too |
| 36 | return 29 |
| 37 | } |
| 38 | ``` |
| 39 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 40 | </div> |
| 41 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 42 | |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 43 | What do we do if we need them to be invoked _sequentially_ — first `doSomethingUsefulOne` _and then_ |
| 44 | `doSomethingUsefulTwo`, and compute the sum of their results? |
| 45 | In practice we do this if we use the result of the first function to make a decision on whether we need |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 46 | to invoke the second one or to decide on how to invoke it. |
| 47 | |
| 48 | We use a normal sequential invocation, because the code in the coroutine, just like in the regular |
| 49 | code, is _sequential_ by default. The following example demonstrates it by measuring the total |
| 50 | time it takes to execute both suspending functions: |
| 51 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 52 | <!--- CLEAR --> |
| 53 | |
| 54 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 55 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 56 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 57 | import kotlinx.coroutines.* |
| 58 | import kotlin.system.* |
| 59 | |
| 60 | fun main() = runBlocking<Unit> { |
| 61 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 62 | val time = measureTimeMillis { |
| 63 | val one = doSomethingUsefulOne() |
| 64 | val two = doSomethingUsefulTwo() |
| 65 | println("The answer is ${one + two}") |
| 66 | } |
| 67 | println("Completed in $time ms") |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 68 | //sampleEnd |
| 69 | } |
| 70 | |
| 71 | suspend fun doSomethingUsefulOne(): Int { |
| 72 | delay(1000L) // pretend we are doing something useful here |
| 73 | return 13 |
| 74 | } |
| 75 | |
| 76 | suspend fun doSomethingUsefulTwo(): Int { |
| 77 | delay(1000L) // pretend we are doing something useful here, too |
| 78 | return 29 |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 79 | } |
| 80 | ``` |
| 81 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 82 | </div> |
| 83 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame] | 84 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-compose-01.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 85 | |
| 86 | It produces something like this: |
| 87 | |
| 88 | ```text |
| 89 | The answer is 42 |
| 90 | Completed in 2017 ms |
| 91 | ``` |
| 92 | |
| 93 | <!--- TEST ARBITRARY_TIME --> |
| 94 | |
| 95 | ### Concurrent using async |
| 96 | |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 97 | What if there are no dependencies between invocations of `doSomethingUsefulOne` and `doSomethingUsefulTwo` and |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 98 | we want to get the answer faster, by doing both _concurrently_? This is where [async] comes to help. |
| 99 | |
| 100 | Conceptually, [async] is just like [launch]. It starts a separate coroutine which is a light-weight thread |
| 101 | that works concurrently with all the other coroutines. The difference is that `launch` returns a [Job] and |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 102 | does not carry any resulting value, while `async` returns a [Deferred] — a light-weight non-blocking future |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 103 | that represents a promise to provide a result later. You can use `.await()` on a deferred value to get its eventual result, |
| 104 | but `Deferred` is also a `Job`, so you can cancel it if needed. |
| 105 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 106 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 107 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 108 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 109 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 110 | import kotlinx.coroutines.* |
| 111 | import kotlin.system.* |
| 112 | |
| 113 | fun main() = runBlocking<Unit> { |
| 114 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 115 | val time = measureTimeMillis { |
| 116 | val one = async { doSomethingUsefulOne() } |
| 117 | val two = async { doSomethingUsefulTwo() } |
| 118 | println("The answer is ${one.await() + two.await()}") |
| 119 | } |
| 120 | println("Completed in $time ms") |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 121 | //sampleEnd |
| 122 | } |
| 123 | |
| 124 | suspend fun doSomethingUsefulOne(): Int { |
| 125 | delay(1000L) // pretend we are doing something useful here |
| 126 | return 13 |
| 127 | } |
| 128 | |
| 129 | suspend fun doSomethingUsefulTwo(): Int { |
| 130 | delay(1000L) // pretend we are doing something useful here, too |
| 131 | return 29 |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 132 | } |
| 133 | ``` |
| 134 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 135 | </div> |
| 136 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame] | 137 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-compose-02.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 138 | |
| 139 | It produces something like this: |
| 140 | |
| 141 | ```text |
| 142 | The answer is 42 |
| 143 | Completed in 1017 ms |
| 144 | ``` |
| 145 | |
| 146 | <!--- TEST ARBITRARY_TIME --> |
| 147 | |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 148 | This is twice as fast, because the two coroutines execute concurrently. |
Inego | ebe519a | 2019-04-21 13:22:27 +0700 | [diff] [blame] | 149 | Note that concurrency with coroutines is always explicit. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 150 | |
| 151 | ### Lazily started async |
| 152 | |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 153 | Optionally, [async] can be made lazy by setting its `start` parameter to [CoroutineStart.LAZY]. |
| 154 | In this mode it only starts the coroutine when its result is required by |
| 155 | [await][Deferred.await], or if its `Job`'s [start][Job.start] function |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 156 | is invoked. Run the following example: |
| 157 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 158 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 159 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 160 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 161 | import kotlinx.coroutines.* |
| 162 | import kotlin.system.* |
| 163 | |
| 164 | fun main() = runBlocking<Unit> { |
| 165 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 166 | val time = measureTimeMillis { |
| 167 | val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() } |
| 168 | val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() } |
| 169 | // some computation |
| 170 | one.start() // start the first one |
| 171 | two.start() // start the second one |
| 172 | println("The answer is ${one.await() + two.await()}") |
| 173 | } |
| 174 | println("Completed in $time ms") |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 175 | //sampleEnd |
| 176 | } |
| 177 | |
| 178 | suspend fun doSomethingUsefulOne(): Int { |
| 179 | delay(1000L) // pretend we are doing something useful here |
| 180 | return 13 |
| 181 | } |
| 182 | |
| 183 | suspend fun doSomethingUsefulTwo(): Int { |
| 184 | delay(1000L) // pretend we are doing something useful here, too |
| 185 | return 29 |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 186 | } |
| 187 | ``` |
| 188 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 189 | </div> |
| 190 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame] | 191 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-compose-03.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 192 | |
| 193 | It produces something like this: |
| 194 | |
| 195 | ```text |
| 196 | The answer is 42 |
| 197 | Completed in 1017 ms |
| 198 | ``` |
| 199 | |
| 200 | <!--- TEST ARBITRARY_TIME --> |
| 201 | |
| 202 | So, here the two coroutines are defined but not executed as in the previous example, but the control is given to |
| 203 | the programmer on when exactly to start the execution by calling [start][Job.start]. We first |
| 204 | start `one`, then start `two`, and then await for the individual coroutines to finish. |
| 205 | |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 206 | Note that if we just call [await][Deferred.await] in `println` without first calling [start][Job.start] on individual |
| 207 | coroutines, this will lead to sequential behavior, since [await][Deferred.await] starts the coroutine |
| 208 | execution and waits for its finish, which is not the intended use-case for laziness. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 209 | The use-case for `async(start = CoroutineStart.LAZY)` is a replacement for the |
| 210 | standard `lazy` function in cases when computation of the value involves suspending functions. |
| 211 | |
| 212 | ### Async-style functions |
| 213 | |
| 214 | We can define async-style functions that invoke `doSomethingUsefulOne` and `doSomethingUsefulTwo` |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 215 | _asynchronously_ using the [async] coroutine builder with an explicit [GlobalScope] reference. |
| 216 | We name such functions with the |
| 217 | "...Async" suffix to highlight the fact that they only start asynchronous computation and one needs |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 218 | to use the resulting deferred value to get the result. |
| 219 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 220 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 221 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 222 | ```kotlin |
| 223 | // The result type of somethingUsefulOneAsync is Deferred<Int> |
| 224 | fun somethingUsefulOneAsync() = GlobalScope.async { |
| 225 | doSomethingUsefulOne() |
| 226 | } |
| 227 | |
| 228 | // The result type of somethingUsefulTwoAsync is Deferred<Int> |
| 229 | fun somethingUsefulTwoAsync() = GlobalScope.async { |
| 230 | doSomethingUsefulTwo() |
| 231 | } |
| 232 | ``` |
| 233 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 234 | </div> |
| 235 | |
Inego | ebe519a | 2019-04-21 13:22:27 +0700 | [diff] [blame] | 236 | Note that these `xxxAsync` functions are **not** _suspending_ functions. They can be used from anywhere. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 237 | However, their use always implies asynchronous (here meaning _concurrent_) execution of their action |
| 238 | with the invoking code. |
| 239 | |
| 240 | The following example shows their use outside of coroutine: |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 241 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 242 | <!--- CLEAR --> |
| 243 | |
| 244 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 245 | |
| 246 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 247 | import kotlinx.coroutines.* |
| 248 | import kotlin.system.* |
| 249 | |
| 250 | //sampleStart |
Inego | ebe519a | 2019-04-21 13:22:27 +0700 | [diff] [blame] | 251 | // note that we don't have `runBlocking` to the right of `main` in this example |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 252 | fun main() { |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 253 | val time = measureTimeMillis { |
| 254 | // we can initiate async actions outside of a coroutine |
| 255 | val one = somethingUsefulOneAsync() |
| 256 | val two = somethingUsefulTwoAsync() |
| 257 | // but waiting for a result must involve either suspending or blocking. |
| 258 | // here we use `runBlocking { ... }` to block the main thread while waiting for the result |
| 259 | runBlocking { |
| 260 | println("The answer is ${one.await() + two.await()}") |
| 261 | } |
| 262 | } |
| 263 | println("Completed in $time ms") |
| 264 | } |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 265 | //sampleEnd |
| 266 | |
| 267 | fun somethingUsefulOneAsync() = GlobalScope.async { |
| 268 | doSomethingUsefulOne() |
| 269 | } |
| 270 | |
| 271 | fun somethingUsefulTwoAsync() = GlobalScope.async { |
| 272 | doSomethingUsefulTwo() |
| 273 | } |
| 274 | |
| 275 | suspend fun doSomethingUsefulOne(): Int { |
| 276 | delay(1000L) // pretend we are doing something useful here |
| 277 | return 13 |
| 278 | } |
| 279 | |
| 280 | suspend fun doSomethingUsefulTwo(): Int { |
| 281 | delay(1000L) // pretend we are doing something useful here, too |
| 282 | return 29 |
| 283 | } |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 284 | ``` |
| 285 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 286 | </div> |
| 287 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame] | 288 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-compose-04.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 289 | |
| 290 | <!--- TEST ARBITRARY_TIME |
| 291 | The answer is 42 |
| 292 | Completed in 1085 ms |
| 293 | --> |
| 294 | |
| 295 | > This programming style with async functions is provided here only for illustration, because it is a popular style |
| 296 | in other programming languages. Using this style with Kotlin coroutines is **strongly discouraged** for the |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 297 | reasons explained below. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 298 | |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 299 | Consider what happens if between the `val one = somethingUsefulOneAsync()` line and `one.await()` expression there is some logic |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 300 | error in the code and the program throws an exception and the operation that was being performed by the program aborts. |
| 301 | Normally, a global error-handler could catch this exception, log and report the error for developers, but the program |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 302 | could otherwise continue doing other operations. But here we have `somethingUsefulOneAsync` still running in the background, |
| 303 | even though the operation that initiated it was aborted. This problem does not happen with structured |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 304 | concurrency, as shown in the section below. |
| 305 | |
| 306 | ### Structured concurrency with async |
| 307 | |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 308 | Let us take the [Concurrent using async](#concurrent-using-async) example and extract a function that |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 309 | concurrently performs `doSomethingUsefulOne` and `doSomethingUsefulTwo` and returns the sum of their results. |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 310 | Because the [async] coroutine builder is defined as an extension on [CoroutineScope], we need to have it in the |
Roman Elizarov | eb1b5db | 2020-10-16 10:45:08 +0300 | [diff] [blame] | 311 | scope and that is what the [coroutineScope][_coroutineScope] function provides: |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 312 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 313 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 314 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 315 | ```kotlin |
| 316 | suspend fun concurrentSum(): Int = coroutineScope { |
| 317 | val one = async { doSomethingUsefulOne() } |
| 318 | val two = async { doSomethingUsefulTwo() } |
Benoît Quenaudon | f62acb6 | 2019-01-29 11:35:13 -0500 | [diff] [blame] | 319 | one.await() + two.await() |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 320 | } |
| 321 | ``` |
| 322 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 323 | </div> |
| 324 | |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 325 | This way, if something goes wrong inside the code of the `concurrentSum` function and it throws an exception, |
| 326 | all the coroutines that were launched in its scope will be cancelled. |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 327 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 328 | <!--- CLEAR --> |
| 329 | |
| 330 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 331 | |
| 332 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 333 | import kotlinx.coroutines.* |
| 334 | import kotlin.system.* |
| 335 | |
| 336 | fun main() = runBlocking<Unit> { |
Roman Elizarov | dbb75d8 | 2019-02-20 13:28:40 +0300 | [diff] [blame] | 337 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 338 | val time = measureTimeMillis { |
| 339 | println("The answer is ${concurrentSum()}") |
| 340 | } |
| 341 | println("Completed in $time ms") |
Roman Elizarov | dbb75d8 | 2019-02-20 13:28:40 +0300 | [diff] [blame] | 342 | //sampleEnd |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 343 | } |
| 344 | |
| 345 | suspend fun concurrentSum(): Int = coroutineScope { |
| 346 | val one = async { doSomethingUsefulOne() } |
| 347 | val two = async { doSomethingUsefulTwo() } |
Benoît Quenaudon | f62acb6 | 2019-01-29 11:35:13 -0500 | [diff] [blame] | 348 | one.await() + two.await() |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 349 | } |
| 350 | |
| 351 | suspend fun doSomethingUsefulOne(): Int { |
| 352 | delay(1000L) // pretend we are doing something useful here |
| 353 | return 13 |
| 354 | } |
| 355 | |
| 356 | suspend fun doSomethingUsefulTwo(): Int { |
| 357 | delay(1000L) // pretend we are doing something useful here, too |
| 358 | return 29 |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 359 | } |
| 360 | ``` |
| 361 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 362 | </div> |
| 363 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame] | 364 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-compose-05.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 365 | |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 366 | We still have concurrent execution of both operations, as evident from the output of the above `main` function: |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 367 | |
| 368 | ```text |
| 369 | The answer is 42 |
| 370 | Completed in 1017 ms |
| 371 | ``` |
| 372 | |
| 373 | <!--- TEST ARBITRARY_TIME --> |
| 374 | |
| 375 | Cancellation is always propagated through coroutines hierarchy: |
| 376 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 377 | <!--- CLEAR --> |
| 378 | |
| 379 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 380 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 381 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 382 | import kotlinx.coroutines.* |
| 383 | |
| 384 | fun main() = runBlocking<Unit> { |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 385 | try { |
| 386 | failedConcurrentSum() |
| 387 | } catch(e: ArithmeticException) { |
| 388 | println("Computation failed with ArithmeticException") |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | suspend fun failedConcurrentSum(): Int = coroutineScope { |
| 393 | val one = async<Int> { |
| 394 | try { |
| 395 | delay(Long.MAX_VALUE) // Emulates very long computation |
| 396 | 42 |
| 397 | } finally { |
| 398 | println("First child was cancelled") |
| 399 | } |
| 400 | } |
| 401 | val two = async<Int> { |
| 402 | println("Second child throws an exception") |
| 403 | throw ArithmeticException() |
| 404 | } |
Benoît Quenaudon | f62acb6 | 2019-01-29 11:35:13 -0500 | [diff] [blame] | 405 | one.await() + two.await() |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 406 | } |
| 407 | ``` |
| 408 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 409 | </div> |
| 410 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame] | 411 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-compose-06.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 412 | |
Yanis Batura | 8ab2130 | 2019-08-08 16:51:03 +0700 | [diff] [blame] | 413 | Note how both the first `async` and the awaiting parent are cancelled on failure of one of the children |
| 414 | (namely, `two`): |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 415 | ```text |
| 416 | Second child throws an exception |
| 417 | First child was cancelled |
| 418 | Computation failed with ArithmeticException |
| 419 | ``` |
| 420 | |
| 421 | <!--- TEST --> |
| 422 | |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 423 | <!--- MODULE kotlinx-coroutines-core --> |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 424 | <!--- INDEX kotlinx.coroutines --> |
Vsevolod Tolstopyatov | 167c44e | 2020-11-30 05:36:23 -0800 | [diff] [blame] | 425 | |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 426 | [async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html |
| 427 | [launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html |
| 428 | [Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html |
| 429 | [Deferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html |
| 430 | [CoroutineStart.LAZY]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-start/-l-a-z-y.html |
| 431 | [Deferred.await]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/await.html |
| 432 | [Job.start]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/start.html |
| 433 | [GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html |
| 434 | [CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html |
Roman Elizarov | eb1b5db | 2020-10-16 10:45:08 +0300 | [diff] [blame] | 435 | [_coroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html |
Vsevolod Tolstopyatov | 167c44e | 2020-11-30 05:36:23 -0800 | [diff] [blame] | 436 | |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 437 | <!--- END --> |