Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 1 | # Guide to kotlinx.coroutines by example |
| 2 | |
| 3 | This is a short guide on core features of `kotlinx.coroutines` with a series of examples. |
| 4 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 5 | ## Table of contents |
| 6 | |
| 7 | * [Coroutine basics](#coroutine-basics) |
| 8 | * [Your first coroutine](#your-first-coroutine) |
| 9 | * [Bridging blocking and non-blocking worlds](#bridging-blocking-and-non-blocking-worlds) |
| 10 | * [Waiting for a job](#waiting-for-a-job) |
| 11 | * [Extract function refactoring](#extract-function-refactoring) |
| 12 | * [Coroutines ARE light-weight](#coroutines-are-light-weight) |
| 13 | * [Coroutines are like daemon threads](#coroutines-are-like-daemon-threads) |
| 14 | * [Cancellation and timeouts](#cancellation-and-timeouts) |
| 15 | * [Cancelling coroutine execution](#cancelling-coroutine-execution) |
| 16 | * [Cancellation is cooperative](#cancellation-is-cooperative) |
| 17 | * [Making computation code cancellable](#making-computation-code-cancellable) |
| 18 | * [Closing resources with finally](#closing-resources-with-finally) |
| 19 | * [Run non-cancellable block](#run-non-cancellable-block) |
| 20 | * [Timeout](#timeout) |
| 21 | * [Composing suspending functions](#composing-suspending-functions) |
| 22 | * [Sequential by default](#sequential-by-default) |
| 23 | * [Concurrent using deferred value](#concurrent-using-deferred-value) |
| 24 | * [Lazily deferred value](#lazily-deferred-value) |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 25 | |
| 26 | <!--- KNIT kotlinx-coroutines-core/src/test/kotlin/guide/.*\.kt --> |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 27 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 28 | <!--- INCLUDE .*/example-([0-9]+)\.kt |
| 29 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
| 30 | package guide.example$$1 |
| 31 | |
| 32 | import kotlinx.coroutines.experimental.* |
| 33 | --> |
| 34 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 35 | ## Coroutine basics |
| 36 | |
| 37 | This section covers basic coroutine concepts. |
| 38 | |
| 39 | ### Your first coroutine |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 40 | |
| 41 | Run the following code: |
| 42 | |
| 43 | ```kotlin |
| 44 | fun main(args: Array<String>) { |
| 45 | launch(CommonPool) { // create new coroutine in common thread pool |
| 46 | delay(1000L) // non-blocking delay for 1 second (default time unit is ms) |
| 47 | println("World!") // print after delay |
| 48 | } |
| 49 | println("Hello,") // main function continues while coroutine is delayed |
| 50 | Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive |
| 51 | } |
| 52 | ``` |
| 53 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 54 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-11.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 55 | |
| 56 | Run this code: |
| 57 | |
| 58 | ``` |
| 59 | Hello, |
| 60 | World! |
| 61 | ``` |
| 62 | |
| 63 | Essentially, coroutines are light-weight threads. You can achieve the same result replacing |
| 64 | `launch(CommonPool) { ... }` with `thread { ... }` and `delay(...)` with `Thread.sleep(...)`. Try it. |
| 65 | |
| 66 | If you start by replacing `launch(CommonPool)` by `thread`, the compiler produces the following error: |
| 67 | |
| 68 | ``` |
| 69 | Error: Kotlin: Suspend functions are only allowed to be called from a coroutine or another suspend function |
| 70 | ``` |
| 71 | |
| 72 | That is because `delay` is a special _suspending function_ that does not block a thread, but _suspends_ |
| 73 | coroutine and it can be only used from a coroutine. |
| 74 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 75 | ### Bridging blocking and non-blocking worlds |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 76 | |
| 77 | The first example mixes _non-blocking_ `delay(...)` and _blocking_ `Thread.sleep(...)` in the same |
| 78 | code of `main` function. It is easy to get lost. Let's cleanly separate blocking and non-blocking |
| 79 | worlds by using `runBlocking { ... }`: |
| 80 | |
| 81 | ```kotlin |
| 82 | fun main(args: Array<String>) = runBlocking<Unit> { // start main coroutine |
| 83 | launch(CommonPool) { // create new coroutine in common thread pool |
| 84 | delay(1000L) |
| 85 | println("World!") |
| 86 | } |
| 87 | println("Hello,") // main coroutine continues while child is delayed |
| 88 | delay(2000L) // non-blocking delay for 2 seconds to keep JVM alive |
| 89 | } |
| 90 | ``` |
| 91 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 92 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-12.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 93 | |
| 94 | The result is the same, but this code uses only non-blocking `delay`. |
| 95 | |
| 96 | `runBlocking { ... }` works as an adaptor that is used here to start the top-level main coroutine. |
| 97 | The regular code outside of `runBlocking` _blocks_, until the coroutine inside `runBlocking` is active. |
| 98 | |
| 99 | This is also a way to write unit-tests for suspending functions: |
| 100 | |
| 101 | ```kotlin |
| 102 | class MyTest { |
| 103 | @Test |
| 104 | fun testMySuspendingFunction() = runBlocking<Unit> { |
| 105 | // here we can use suspending functions using any assertion style that we like |
| 106 | } |
| 107 | } |
| 108 | ``` |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 109 | |
| 110 | <!--- CLEAR --> |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 111 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 112 | ### Waiting for a job |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 113 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 114 | Delaying for a time while another coroutine is working is not a good approach. Let's explicitly |
| 115 | wait (in a non-blocking way) until the background job coroutine that we have launched is complete: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 116 | |
| 117 | ```kotlin |
| 118 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 119 | val job = launch(CommonPool) { // create new coroutine and keep a reference to its Job |
| 120 | delay(1000L) |
| 121 | println("World!") |
| 122 | } |
| 123 | println("Hello,") |
| 124 | job.join() // wait until child coroutine completes |
| 125 | } |
| 126 | ``` |
| 127 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 128 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-13.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 129 | |
| 130 | Now the result is still the same, but the code of the main coroutine is not tied to the duration of |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 131 | the background job in any way. Much better. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 132 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 133 | ### Extract function refactoring |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 134 | |
| 135 | Let's extract the block of code inside `launch(CommonPool} { ... }` into a separate function. When you |
| 136 | perform "Extract function" refactoring on this code you get a new function with `suspend` modifier. |
| 137 | That is your first _suspending function_. Suspending functions can be used inside coroutines |
| 138 | just like regular functions, but their additional feature is that they can, in turn, |
| 139 | use other suspending functions, like `delay` in this example, to _suspend_ execution of a coroutine. |
| 140 | |
| 141 | ```kotlin |
| 142 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 143 | val job = launch(CommonPool) { doWorld() } |
| 144 | println("Hello,") |
| 145 | job.join() |
| 146 | } |
| 147 | |
| 148 | // this is your first suspending function |
| 149 | suspend fun doWorld() { |
| 150 | delay(1000L) |
| 151 | println("World!") |
| 152 | } |
| 153 | ``` |
| 154 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 155 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-14.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 156 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 157 | ### Coroutines ARE light-weight |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 158 | |
| 159 | Run the following code: |
| 160 | |
| 161 | ```kotlin |
| 162 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 163 | val jobs = List(100_000) { // create a lot of coroutines and list their jobs |
| 164 | launch(CommonPool) { |
| 165 | delay(1000L) |
| 166 | print(".") |
| 167 | } |
| 168 | } |
| 169 | jobs.forEach { it.join() } // wait for all jobs to complete |
| 170 | } |
| 171 | ``` |
| 172 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 173 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-15.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 174 | |
| 175 | It starts 100K coroutines and, after a second, each coroutine prints a dot. |
| 176 | Now, try that with threads. What would happen? (Most likely your code will produce some sort of out-of-memory error) |
| 177 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 178 | ### Coroutines are like daemon threads |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 179 | |
| 180 | The following code launches a long-running coroutine that prints "I'm sleeping" twice a second and then |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 181 | returns from the main function after some delay: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 182 | |
| 183 | ```kotlin |
| 184 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 185 | launch(CommonPool) { |
| 186 | repeat(1000) { i -> |
| 187 | println("I'm sleeping $i ...") |
| 188 | delay(500L) |
| 189 | } |
| 190 | } |
| 191 | delay(1300L) // just quit after delay |
| 192 | } |
| 193 | ``` |
| 194 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 195 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-16.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 196 | |
| 197 | You can run and see that it prints three lines and terminates: |
| 198 | |
| 199 | ``` |
| 200 | I'm sleeping 0 ... |
| 201 | I'm sleeping 1 ... |
| 202 | I'm sleeping 2 ... |
| 203 | ``` |
| 204 | |
| 205 | Active coroutines do not keep the process alive. They are like daemon threads. |
| 206 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 207 | ## Cancellation and timeouts |
| 208 | |
| 209 | This section covers coroutine cancellation and timeouts. |
| 210 | |
| 211 | ### Cancelling coroutine execution |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 212 | |
| 213 | In small application the return from "main" method might sound like a good idea to get all coroutines |
| 214 | implicitly terminated. In a larger, long-running application, you need finer-grained control. |
| 215 | The `launch` function returns a `Job` that can be used to cancel running coroutine: |
| 216 | |
| 217 | ```kotlin |
| 218 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 219 | val job = launch(CommonPool) { |
| 220 | repeat(1000) { i -> |
| 221 | println("I'm sleeping $i ...") |
| 222 | delay(500L) |
| 223 | } |
| 224 | } |
| 225 | delay(1300L) // delay a bit |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 226 | println("main: I'm tired of waiting!") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 227 | job.cancel() // cancels the job |
| 228 | delay(1300L) // delay a bit to ensure it was cancelled indeed |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 229 | println("main: Now I can quit.") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 230 | } |
| 231 | ``` |
| 232 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 233 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-21.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 234 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 235 | It produces the following output: |
| 236 | |
| 237 | ``` |
| 238 | I'm sleeping 0 ... |
| 239 | I'm sleeping 1 ... |
| 240 | I'm sleeping 2 ... |
| 241 | main: I'm tired of waiting! |
| 242 | main: Now I can quit. |
| 243 | ``` |
| 244 | |
| 245 | As soon as main invokes `job.cancel`, we don't see any output from the other coroutine because it was cancelled. |
| 246 | |
| 247 | ### Cancellation is cooperative |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 248 | |
Tair Rzayev | af73462 | 2017-02-01 22:30:16 +0200 | [diff] [blame] | 249 | Coroutine cancellation is _cooperative_. A coroutine code has to cooperate to be cancellable. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 250 | All the suspending functions in `kotlinx.coroutines` are _cancellable_. They check for cancellation of |
| 251 | coroutine and throw `CancellationException` when cancelled. However, if a coroutine is working in |
| 252 | a computation and does not check for cancellation, then it cannot be cancelled, like the following |
| 253 | example shows: |
| 254 | |
| 255 | ```kotlin |
| 256 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 257 | val job = launch(CommonPool) { |
| 258 | var nextPrintTime = 0L |
| 259 | var i = 0 |
| 260 | while (true) { // computation loop |
| 261 | val currentTime = System.currentTimeMillis() |
| 262 | if (currentTime >= nextPrintTime) { |
| 263 | println("I'm sleeping ${i++} ...") |
| 264 | nextPrintTime = currentTime + 500L |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | delay(1300L) // delay a bit |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 269 | println("main: I'm tired of waiting!") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 270 | job.cancel() // cancels the job |
| 271 | delay(1300L) // delay a bit to see if it was cancelled.... |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 272 | println("main: Now I can quit.") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 273 | } |
| 274 | ``` |
| 275 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 276 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-22.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 277 | |
| 278 | Run it to see that it continues to print "I'm sleeping" even after cancellation. |
| 279 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 280 | ### Making computation code cancellable |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 281 | |
| 282 | There are two approaches to making computation code cancellable. The first one is to periodically |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 283 | invoke a suspending function. There is a `yield` function that is a good choice for that purpose. |
| 284 | The other one is to explicitly check the cancellation status. Let us try the later approach. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 285 | |
| 286 | Replace `while (true)` in the previous example with `while (isActive)` and rerun it. |
| 287 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 288 | ```kotlin |
| 289 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 290 | val job = launch(CommonPool) { |
| 291 | var nextPrintTime = 0L |
| 292 | var i = 0 |
| 293 | while (isActive) { // cancellable computation loop |
| 294 | val currentTime = System.currentTimeMillis() |
| 295 | if (currentTime >= nextPrintTime) { |
| 296 | println("I'm sleeping ${i++} ...") |
| 297 | nextPrintTime = currentTime + 500L |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | delay(1300L) // delay a bit |
| 302 | println("main: I'm tired of waiting!") |
| 303 | job.cancel() // cancels the job |
| 304 | delay(1300L) // delay a bit to see if it was cancelled.... |
| 305 | println("main: Now I can quit.") |
| 306 | } |
| 307 | ``` |
| 308 | |
| 309 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-23.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 310 | |
| 311 | As you can see, now this loop can be cancelled. `isActive` is a property that is available inside |
| 312 | the code of coroutines via `CoroutineScope` object. |
| 313 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 314 | ### Closing resources with finally |
| 315 | |
| 316 | Cancellable suspending functions throw `CancellationException` on cancellation which can be handled in |
| 317 | all the usual way. For example, the `try {...} finally {...}` and Kotlin `use` function execute their |
| 318 | finalization actions normally when coroutine is cancelled: |
| 319 | |
| 320 | ```kotlin |
| 321 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 322 | val job = launch(CommonPool) { |
| 323 | try { |
| 324 | repeat(1000) { i -> |
| 325 | println("I'm sleeping $i ...") |
| 326 | delay(500L) |
| 327 | } |
| 328 | } finally { |
| 329 | println("I'm running finally") |
| 330 | } |
| 331 | } |
| 332 | delay(1300L) // delay a bit |
| 333 | println("main: I'm tired of waiting!") |
| 334 | job.cancel() // cancels the job |
| 335 | delay(1300L) // delay a bit to ensure it was cancelled indeed |
| 336 | println("main: Now I can quit.") |
| 337 | } |
| 338 | ``` |
| 339 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 340 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-24.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 341 | |
| 342 | The example above produces the following output: |
| 343 | |
| 344 | ``` |
| 345 | I'm sleeping 0 ... |
| 346 | I'm sleeping 1 ... |
| 347 | I'm sleeping 2 ... |
| 348 | main: I'm tired of waiting! |
| 349 | I'm running finally |
| 350 | main: Now I can quit. |
| 351 | ``` |
| 352 | |
| 353 | ### Run non-cancellable block |
| 354 | |
| 355 | Any attempt to use a suspending function in the `finally` block of the previous example will cause |
| 356 | `CancellationException`, because the coroutine running this code is cancelled. Usually, this is not a |
| 357 | problem, since all well-behaving closing operations (closing a file, cancelling a job, or closing any kind of a |
| 358 | communication channel) are usually non-blocking and do not involve any suspending functions. However, in the |
| 359 | rare case when you need to suspend in the cancelled coroutine you can wrap the corresponding code in |
| 360 | `run(NonCancellable) {...}` as the following example shows: |
| 361 | |
| 362 | ```kotlin |
| 363 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 364 | val job = launch(CommonPool) { |
| 365 | try { |
| 366 | repeat(1000) { i -> |
| 367 | println("I'm sleeping $i ...") |
| 368 | delay(500L) |
| 369 | } |
| 370 | } finally { |
| 371 | run(NonCancellable) { |
| 372 | println("I'm running finally") |
| 373 | delay(1000L) |
| 374 | println("And I've just delayed for 1 sec because I'm non-cancellable") |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | delay(1300L) // delay a bit |
| 379 | println("main: I'm tired of waiting!") |
| 380 | job.cancel() // cancels the job |
| 381 | delay(1300L) // delay a bit to ensure it was cancelled indeed |
| 382 | println("main: Now I can quit.") |
| 383 | } |
| 384 | ``` |
| 385 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 386 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-25.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 387 | |
| 388 | ### Timeout |
| 389 | |
| 390 | The most obvious reason to cancel coroutine execution in practice, |
| 391 | is because its execution time has exceeded some timeout. |
| 392 | While you can manually track the reference to the corresponding `job` and launch a separate coroutine to cancel |
| 393 | the tracked one after delay, there is a ready to use `withTimeout(...) {...}` function that does it. |
| 394 | Look at the following example: |
| 395 | |
| 396 | ```kotlin |
| 397 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 398 | withTimeout(1300L) { |
| 399 | repeat(1000) { i -> |
| 400 | println("I'm sleeping $i ...") |
| 401 | delay(500L) |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | ``` |
| 406 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 407 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-26.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 408 | |
| 409 | It produces the following output: |
| 410 | |
| 411 | ``` |
| 412 | I'm sleeping 0 ... |
| 413 | I'm sleeping 1 ... |
| 414 | I'm sleeping 2 ... |
| 415 | Exception in thread "main" java.util.concurrent.CancellationException: Timed out waiting for 1300 MILLISECONDS |
| 416 | ``` |
| 417 | |
| 418 | We have not seen the `CancellationException` stack trace printed on the console before. That is because |
| 419 | inside a cancelled coroutine `CancellationException` is a considered a normal reason for coroutine completion. |
| 420 | However, in this example we have used `withTimeout` right inside the `main` function. |
| 421 | |
| 422 | Because cancellation is just an exception, all the resources will be closed in a usual way. |
| 423 | You can wrap the code with timeout in `try {...} catch (e: CancellationException) {...}` block if |
| 424 | you need to do some additional action specifically on timeout. |
| 425 | |
| 426 | ## Composing suspending functions |
| 427 | |
| 428 | This section covers various approaches to composition of suspending functions. |
| 429 | |
| 430 | ### Sequential by default |
| 431 | |
| 432 | Assume that we have two suspending functions defined elsewhere that do something useful like some kind of |
| 433 | remote service call or computation. We'll just pretend they are useful, but each one will just actaully |
| 434 | delay for a second for the purpose of this example: |
| 435 | |
| 436 | ```kotlin |
| 437 | suspend fun doSomethingUsefulOne(): Int { |
| 438 | delay(1000L) // pretend we are doing something useful here |
| 439 | return 13 |
| 440 | } |
| 441 | |
| 442 | suspend fun doSomethingUsefulTwo(): Int { |
| 443 | delay(1000L) // pretend we are doing something useful here, too |
| 444 | return 29 |
| 445 | } |
| 446 | ``` |
| 447 | |
| 448 | What do we do if need to invoke them _sequentially_ -- first `doSomethingUsefulOne` _and then_ |
| 449 | `doSomethingUsefulTwo` and compute the sum of their results? |
| 450 | In practise we do this if we use the results of the first function to make a decision on whether we need |
| 451 | to invoke the second one or to decide on how to invoke it. |
| 452 | |
| 453 | We just use a normal sequential invocation, because the code in the coroutine, just like in the regular |
| 454 | code, is _sequential_ by default. The following example demonstrates that by measuring the total |
| 455 | time it takes to execute both suspending functions: |
| 456 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 457 | <!--- INCLUDE .*/example-3[1-9].kt |
| 458 | import kotlin.system.measureTimeMillis |
| 459 | --> |
| 460 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 461 | ```kotlin |
| 462 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 463 | val time = measureTimeMillis { |
| 464 | val one = doSomethingUsefulOne() |
| 465 | val two = doSomethingUsefulTwo() |
| 466 | println("The answer is ${one + two}") |
| 467 | } |
| 468 | println("Completed in $time ms") |
| 469 | } |
| 470 | ``` |
| 471 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 472 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-31.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 473 | |
| 474 | It produces something like this: |
| 475 | |
| 476 | ``` |
| 477 | The answer is 42 |
| 478 | Completed in 2017 ms |
| 479 | ``` |
| 480 | |
| 481 | ### Concurrent using deferred value |
| 482 | |
| 483 | What if there are no dependencies between invocation of `doSomethingUsefulOne` and `doSomethingUsefulTwo` and |
| 484 | we want to get the answer faster, by doing both _concurrently_? This is where `defer` comes to helps. |
| 485 | |
| 486 | Conceptually, `defer` is just like `launch`. It starts a separate coroutine which is a light-weight thread |
| 487 | that works concurrently with all the other coroutines. The difference is that `launch` returns a `Job` and |
| 488 | does not carry any resulting value, while `defer` returns a `Deferred` -- a kind of light-weight non-blocking future |
| 489 | that represent a promise to provide result later. You can use `.await()` on a deferred value to get its eventual result, |
| 490 | but `Deferred` is also a `Job`, so you can cancel it if needed. |
| 491 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 492 | <!--- INCLUDE .*/example-3[2-9].kt |
| 493 | |
| 494 | suspend fun doSomethingUsefulOne(): Int { |
| 495 | delay(1000L) // pretend we are doing something useful here |
| 496 | return 13 |
| 497 | } |
| 498 | |
| 499 | suspend fun doSomethingUsefulTwo(): Int { |
| 500 | delay(1000L) // pretend we are doing something useful here, too |
| 501 | return 29 |
| 502 | } |
| 503 | --> |
| 504 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 505 | ```kotlin |
| 506 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 507 | val time = measureTimeMillis { |
| 508 | val one = defer(CommonPool) { doSomethingUsefulOne() } |
| 509 | val two = defer(CommonPool) { doSomethingUsefulTwo() } |
| 510 | println("The answer is ${one.await() + two.await()}") |
| 511 | } |
| 512 | println("Completed in $time ms") |
| 513 | } |
| 514 | ``` |
| 515 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 516 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-32.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 517 | |
| 518 | It produces something like this: |
| 519 | |
| 520 | ``` |
| 521 | The answer is 42 |
| 522 | Completed in 1017 ms |
| 523 | ``` |
| 524 | |
| 525 | This is twice as fast, because we have concurrent execution of two coroutines. |
| 526 | Note, that concurrency with coroutines is always explicit. |
| 527 | |
| 528 | ### Lazily deferred value |
| 529 | |
| 530 | There is a lazy alternative to `defer` that is called `lazyDefer`. It is just like `defer`, but it |
| 531 | starts coroutine only when its result is needed by some `await` or if a special `start` function |
| 532 | is invoked. Run the following example: |
| 533 | |
| 534 | ```kotlin |
| 535 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 536 | val time = measureTimeMillis { |
| 537 | val one = lazyDefer(CommonPool) { doSomethingUsefulOne() } |
| 538 | val two = lazyDefer(CommonPool) { doSomethingUsefulTwo() } |
| 539 | println("The answer is ${one.await() + two.await()}") |
| 540 | } |
| 541 | println("Completed in $time ms") |
| 542 | } |
| 543 | ``` |
| 544 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame^] | 545 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-33.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 546 | |
| 547 | It produces something like this: |
| 548 | |
| 549 | ``` |
| 550 | The answer is 42 |
| 551 | Completed in 2017 ms |
| 552 | ``` |
| 553 | |
| 554 | So, we are back to two sequential execution, because we _first_ await for the `one` deferred, _and then_ await |
| 555 | for the second one. It is not the intended use-case for `lazyDefer`. It is designed as a replacement for |
| 556 | the standard `lazy` function in cases when computation of the value involve suspending functions. |
| 557 | |
| 558 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 559 | |