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