hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 1 | <!--- INCLUDE .*/example-([a-z]+)-([0-9a-z]+)\.kt |
| 2 | /* |
Roman Elizarov | db0ef0c | 2019-07-03 15:02:44 +0300 | [diff] [blame] | 3 | * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 4 | */ |
| 5 | |
| 6 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 7 | package kotlinx.coroutines.guide.$$1$$2 |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 8 | --> |
Vsevolod Tolstopyatov | e50a0fa | 2019-01-28 11:34:24 +0300 | [diff] [blame] | 9 | <!--- KNIT ../kotlinx-coroutines-core/jvm/test/guide/.*\.kt --> |
| 10 | <!--- TEST_OUT ../kotlinx-coroutines-core/jvm/test/guide/test/BasicsGuideTest.kt |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 11 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 12 | package kotlinx.coroutines.guide.test |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 13 | |
| 14 | import org.junit.Test |
| 15 | |
| 16 | class BasicsGuideTest { |
| 17 | --> |
| 18 | |
Prendota | b8a559d | 2018-11-30 16:24:23 +0300 | [diff] [blame] | 19 | **Table of contents** |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 20 | |
| 21 | <!--- TOC --> |
| 22 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 23 | * [Coroutine Basics](#coroutine-basics) |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 24 | * [Your first coroutine](#your-first-coroutine) |
| 25 | * [Bridging blocking and non-blocking worlds](#bridging-blocking-and-non-blocking-worlds) |
| 26 | * [Waiting for a job](#waiting-for-a-job) |
| 27 | * [Structured concurrency](#structured-concurrency) |
| 28 | * [Scope builder](#scope-builder) |
| 29 | * [Extract function refactoring](#extract-function-refactoring) |
| 30 | * [Coroutines ARE light-weight](#coroutines-are-light-weight) |
| 31 | * [Global coroutines are like daemon threads](#global-coroutines-are-like-daemon-threads) |
| 32 | |
| 33 | <!--- END_TOC --> |
| 34 | |
| 35 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 36 | ## Coroutine Basics |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 37 | |
| 38 | This section covers basic coroutine concepts. |
| 39 | |
| 40 | ### Your first coroutine |
| 41 | |
| 42 | Run the following code: |
| 43 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 44 | <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] | 45 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 46 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 47 | import kotlinx.coroutines.* |
| 48 | |
| 49 | fun main() { |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 50 | GlobalScope.launch { // launch a new coroutine in background and continue |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 51 | delay(1000L) // non-blocking delay for 1 second (default time unit is ms) |
| 52 | println("World!") // print after delay |
| 53 | } |
| 54 | println("Hello,") // main thread continues while coroutine is delayed |
| 55 | Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive |
| 56 | } |
| 57 | ``` |
| 58 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 59 | </div> |
| 60 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 61 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-basic-01.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 62 | |
Marcin Moskała | e5bf9ae | 2018-10-08 09:59:41 +0300 | [diff] [blame] | 63 | You will see the following result: |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 64 | |
| 65 | ```text |
| 66 | Hello, |
| 67 | World! |
| 68 | ``` |
| 69 | |
| 70 | <!--- TEST --> |
| 71 | |
| 72 | Essentially, coroutines are light-weight threads. |
| 73 | They are launched with [launch] _coroutine builder_ in a context of some [CoroutineScope]. |
| 74 | Here we are launching a new coroutine in the [GlobalScope], meaning that the lifetime of the new |
| 75 | coroutine is limited only by the lifetime of the whole application. |
| 76 | |
| 77 | You can achieve the same result replacing |
Vsevolod Tolstopyatov | 445e026 | 2019-11-25 18:56:24 +0300 | [diff] [blame^] | 78 | `GlobalScope.launch { ... }` with `thread { ... }` and `delay(...)` with `Thread.sleep(...)`. |
| 79 | Try it (don't forget to import `kotlin.concurrent.thread`). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 80 | |
| 81 | If you start by replacing `GlobalScope.launch` by `thread`, the compiler produces the following error: |
| 82 | |
| 83 | ``` |
| 84 | Error: Kotlin: Suspend functions are only allowed to be called from a coroutine or another suspend function |
| 85 | ``` |
| 86 | |
| 87 | That is because [delay] is a special _suspending function_ that does not block a thread, but _suspends_ |
| 88 | coroutine and it can be only used from a coroutine. |
| 89 | |
| 90 | ### Bridging blocking and non-blocking worlds |
| 91 | |
| 92 | The first example mixes _non-blocking_ `delay(...)` and _blocking_ `Thread.sleep(...)` in the same code. |
Devin B | b104cfc | 2018-11-12 11:51:00 -0500 | [diff] [blame] | 93 | It is easy to lose track of which one is blocking and which one is not. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 94 | Let's be explicit about blocking using [runBlocking] coroutine builder: |
| 95 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 96 | <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] | 97 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 98 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 99 | import kotlinx.coroutines.* |
| 100 | |
| 101 | fun main() { |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 102 | GlobalScope.launch { // launch a new coroutine in background and continue |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 103 | delay(1000L) |
| 104 | println("World!") |
| 105 | } |
| 106 | println("Hello,") // main thread continues here immediately |
| 107 | runBlocking { // but this expression blocks the main thread |
| 108 | delay(2000L) // ... while we delay for 2 seconds to keep JVM alive |
| 109 | } |
| 110 | } |
| 111 | ``` |
| 112 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 113 | </div> |
| 114 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 115 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-basic-02.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 116 | |
| 117 | <!--- TEST |
| 118 | Hello, |
| 119 | World! |
| 120 | --> |
| 121 | |
| 122 | The result is the same, but this code uses only non-blocking [delay]. |
Inego | 596187e | 2019-04-21 14:21:53 +0700 | [diff] [blame] | 123 | The main thread invoking `runBlocking` _blocks_ until the coroutine inside `runBlocking` completes. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 124 | |
| 125 | This example can be also rewritten in a more idiomatic way, using `runBlocking` to wrap |
| 126 | the execution of the main function: |
| 127 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 128 | <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] | 129 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 130 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 131 | import kotlinx.coroutines.* |
| 132 | |
| 133 | fun main() = runBlocking<Unit> { // start main coroutine |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 134 | GlobalScope.launch { // launch a new coroutine in background and continue |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 135 | delay(1000L) |
| 136 | println("World!") |
| 137 | } |
| 138 | println("Hello,") // main coroutine continues here immediately |
| 139 | delay(2000L) // delaying for 2 seconds to keep JVM alive |
| 140 | } |
| 141 | ``` |
| 142 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 143 | </div> |
| 144 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 145 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-basic-02b.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 146 | |
| 147 | <!--- TEST |
| 148 | Hello, |
| 149 | World! |
| 150 | --> |
| 151 | |
| 152 | Here `runBlocking<Unit> { ... }` works as an adaptor that is used to start the top-level main coroutine. |
| 153 | We explicitly specify its `Unit` return type, because a well-formed `main` function in Kotlin has to return `Unit`. |
| 154 | |
Inego | 596187e | 2019-04-21 14:21:53 +0700 | [diff] [blame] | 155 | This is also a way to write unit tests for suspending functions: |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 156 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 157 | <!--- INCLUDE |
| 158 | import kotlinx.coroutines.* |
| 159 | --> |
| 160 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 161 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 162 | |
| 163 | ```kotlin |
| 164 | class MyTest { |
| 165 | @Test |
| 166 | fun testMySuspendingFunction() = runBlocking<Unit> { |
| 167 | // here we can use suspending functions using any assertion style that we like |
| 168 | } |
| 169 | } |
| 170 | ``` |
| 171 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 172 | </div> |
| 173 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 174 | <!--- CLEAR --> |
| 175 | |
| 176 | ### Waiting for a job |
| 177 | |
| 178 | Delaying for a time while another coroutine is working is not a good approach. Let's explicitly |
| 179 | wait (in a non-blocking way) until the background [Job] that we have launched is complete: |
| 180 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 181 | <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] | 182 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 183 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 184 | import kotlinx.coroutines.* |
| 185 | |
| 186 | fun main() = runBlocking { |
| 187 | //sampleStart |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 188 | val job = GlobalScope.launch { // launch a new coroutine and keep a reference to its Job |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 189 | delay(1000L) |
| 190 | println("World!") |
| 191 | } |
| 192 | println("Hello,") |
| 193 | job.join() // wait until child coroutine completes |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 194 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 195 | } |
| 196 | ``` |
| 197 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 198 | </div> |
| 199 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 200 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-basic-03.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 201 | |
| 202 | <!--- TEST |
| 203 | Hello, |
| 204 | World! |
| 205 | --> |
| 206 | |
| 207 | Now the result is still the same, but the code of the main coroutine is not tied to the duration of |
| 208 | the background job in any way. Much better. |
| 209 | |
| 210 | ### Structured concurrency |
| 211 | |
| 212 | There is still something to be desired for practical usage of coroutines. |
Inego | 596187e | 2019-04-21 14:21:53 +0700 | [diff] [blame] | 213 | When we use `GlobalScope.launch`, we create a top-level coroutine. Even though it is light-weight, it still |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 214 | consumes some memory resources while it runs. If we forget to keep a reference to the newly launched |
| 215 | coroutine it still runs. What if the code in the coroutine hangs (for example, we erroneously |
| 216 | delay for too long), what if we launched too many coroutines and ran out of memory? |
Inego | 596187e | 2019-04-21 14:21:53 +0700 | [diff] [blame] | 217 | Having to manually keep references to all the launched coroutines and [join][Job.join] them is error-prone. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 218 | |
| 219 | There is a better solution. We can use structured concurrency in our code. |
| 220 | Instead of launching coroutines in the [GlobalScope], just like we usually do with threads (threads are always global), |
| 221 | we can launch coroutines in the specific scope of the operation we are performing. |
| 222 | |
| 223 | In our example, we have `main` function that is turned into a coroutine using [runBlocking] coroutine builder. |
saied89 | a223f35 | 2018-10-30 22:44:20 +0330 | [diff] [blame] | 224 | Every coroutine builder, including `runBlocking`, adds an instance of [CoroutineScope] to the scope of its code block. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 225 | We can launch coroutines in this scope without having to `join` them explicitly, because |
| 226 | an outer coroutine (`runBlocking` in our example) does not complete until all the coroutines launched |
| 227 | in its scope complete. Thus, we can make our example simpler: |
| 228 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 229 | <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] | 230 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 231 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 232 | import kotlinx.coroutines.* |
| 233 | |
| 234 | fun main() = runBlocking { // this: CoroutineScope |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 235 | launch { // launch a new coroutine in the scope of runBlocking |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 236 | delay(1000L) |
| 237 | println("World!") |
| 238 | } |
| 239 | println("Hello,") |
| 240 | } |
| 241 | ``` |
| 242 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 243 | </div> |
| 244 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 245 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-basic-03s.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 246 | |
| 247 | <!--- TEST |
| 248 | Hello, |
| 249 | World! |
| 250 | --> |
| 251 | |
| 252 | ### Scope builder |
| 253 | In addition to the coroutine scope provided by different builders, it is possible to declare your own scope using |
Inego | 6da0ccd | 2019-04-21 14:26:40 +0700 | [diff] [blame] | 254 | [coroutineScope] builder. It creates a coroutine scope and does not complete until all launched children |
Vsevolod Tolstopyatov | e303e6b | 2019-10-09 13:55:57 +0300 | [diff] [blame] | 255 | complete. |
| 256 | |
| 257 | [runBlocking] and [coroutineScope] may look similar because they both wait for its body and all its children to complete. |
| 258 | The main difference between these two is that the [runBlocking] method _blocks_ the current thread for waiting, |
| 259 | while [coroutineScope] just suspends, releasing the underlying thread for other usages. |
| 260 | Because of that difference, [runBlocking] is a regular function and [coroutineScope] is a suspending function. |
| 261 | |
| 262 | It can be demonstrated by the following example: |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 263 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 264 | <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] | 265 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 266 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 267 | import kotlinx.coroutines.* |
| 268 | |
| 269 | fun main() = runBlocking { // this: CoroutineScope |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 270 | launch { |
| 271 | delay(200L) |
| 272 | println("Task from runBlocking") |
| 273 | } |
| 274 | |
Inego | 564a5a6 | 2019-04-21 14:34:55 +0700 | [diff] [blame] | 275 | coroutineScope { // Creates a coroutine scope |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 276 | launch { |
| 277 | delay(500L) |
| 278 | println("Task from nested launch") |
| 279 | } |
| 280 | |
| 281 | delay(100L) |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 282 | println("Task from coroutine scope") // This line will be printed before the nested launch |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 283 | } |
| 284 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 285 | println("Coroutine scope is over") // This line is not printed until the nested launch completes |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 286 | } |
| 287 | ``` |
| 288 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 289 | </div> |
| 290 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 291 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-basic-04.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 292 | |
| 293 | <!--- TEST |
| 294 | Task from coroutine scope |
| 295 | Task from runBlocking |
| 296 | Task from nested launch |
| 297 | Coroutine scope is over |
| 298 | --> |
| 299 | |
Vsevolod Tolstopyatov | e303e6b | 2019-10-09 13:55:57 +0300 | [diff] [blame] | 300 | Note that right after "Task from coroutine scope" message, while waiting for nested launch, |
| 301 | "Task from runBlocking" is executed and printed, though coroutineScope is not completed yet. |
| 302 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 303 | ### Extract function refactoring |
| 304 | |
| 305 | Let's extract the block of code inside `launch { ... }` into a separate function. When you |
| 306 | perform "Extract function" refactoring on this code you get a new function with `suspend` modifier. |
| 307 | That is your first _suspending function_. Suspending functions can be used inside coroutines |
| 308 | just like regular functions, but their additional feature is that they can, in turn, |
| 309 | use other suspending functions, like `delay` in this example, to _suspend_ execution of a coroutine. |
| 310 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 311 | <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] | 312 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 313 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 314 | import kotlinx.coroutines.* |
| 315 | |
| 316 | fun main() = runBlocking { |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 317 | launch { doWorld() } |
| 318 | println("Hello,") |
| 319 | } |
| 320 | |
| 321 | // this is your first suspending function |
| 322 | suspend fun doWorld() { |
| 323 | delay(1000L) |
| 324 | println("World!") |
| 325 | } |
| 326 | ``` |
| 327 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 328 | </div> |
| 329 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 330 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-basic-05.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 331 | |
| 332 | <!--- TEST |
| 333 | Hello, |
| 334 | World! |
| 335 | --> |
| 336 | |
| 337 | |
| 338 | But what if the extracted function contains a coroutine builder which is invoked on the current scope? |
Petter Måhlén | 6130238 | 2019-07-02 08:01:36 +0200 | [diff] [blame] | 339 | In this case `suspend` modifier on the extracted function is not enough. Making `doWorld` an extension |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 340 | method on `CoroutineScope` is one of the solutions, but it may not always be applicable as it does not make API clearer. |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 341 | The idiomatic solution is to have either an explicit `CoroutineScope` as a field in a class containing the target function |
| 342 | or an implicit one when the outer class implements `CoroutineScope`. |
Vsevolod Tolstopyatov | fac516f | 2018-09-28 14:38:29 +0300 | [diff] [blame] | 343 | As a last resort, [CoroutineScope(coroutineContext)][CoroutineScope()] can be used, but such approach is structurally unsafe |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 344 | because you no longer have control on the scope of execution of this method. Only private APIs can use this builder. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 345 | |
| 346 | ### Coroutines ARE light-weight |
| 347 | |
| 348 | Run the following code: |
| 349 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 350 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 351 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 352 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 353 | import kotlinx.coroutines.* |
| 354 | |
| 355 | fun main() = runBlocking { |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 356 | repeat(100_000) { // launch a lot of coroutines |
| 357 | launch { |
| 358 | delay(1000L) |
| 359 | print(".") |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | ``` |
| 364 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 365 | </div> |
| 366 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 367 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-basic-06.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 368 | |
| 369 | <!--- TEST lines.size == 1 && lines[0] == ".".repeat(100_000) --> |
| 370 | |
| 371 | It launches 100K coroutines and, after a second, each coroutine prints a dot. |
| 372 | Now, try that with threads. What would happen? (Most likely your code will produce some sort of out-of-memory error) |
| 373 | |
| 374 | ### Global coroutines are like daemon threads |
| 375 | |
| 376 | The following code launches a long-running coroutine in [GlobalScope] that prints "I'm sleeping" twice a second and then |
| 377 | returns from the main function after some delay: |
| 378 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 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 { |
| 385 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 386 | GlobalScope.launch { |
| 387 | repeat(1000) { i -> |
| 388 | println("I'm sleeping $i ...") |
| 389 | delay(500L) |
| 390 | } |
| 391 | } |
| 392 | delay(1300L) // just quit after delay |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 393 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 394 | } |
| 395 | ``` |
| 396 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 397 | </div> |
| 398 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 399 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-basic-07.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 400 | |
| 401 | You can run and see that it prints three lines and terminates: |
| 402 | |
| 403 | ```text |
| 404 | I'm sleeping 0 ... |
| 405 | I'm sleeping 1 ... |
| 406 | I'm sleeping 2 ... |
| 407 | ``` |
| 408 | |
| 409 | <!--- TEST --> |
| 410 | |
| 411 | Active coroutines that were launched in [GlobalScope] do not keep the process alive. They are like daemon threads. |
| 412 | |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 413 | <!--- MODULE kotlinx-coroutines-core --> |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 414 | <!--- INDEX kotlinx.coroutines --> |
| 415 | [launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html |
| 416 | [CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html |
| 417 | [GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html |
| 418 | [delay]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/delay.html |
| 419 | [runBlocking]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html |
| 420 | [Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html |
| 421 | [Job.join]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/join.html |
| 422 | [coroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html |
| 423 | [CoroutineScope()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope.html |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 424 | <!--- END --> |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 425 | |
| 426 | |