|
| 1 | +# kotlinx.coroutines core tutorial |
| 2 | + |
| 3 | +This is a DRAFT of a very short tutorial on core features of `kotlinx.coroutines`. |
| 4 | + |
| 5 | +## Your first coroutine |
| 6 | + |
| 7 | +Run the following code: |
| 8 | + |
| 9 | +```kotlin |
| 10 | +fun main(args: Array<String>) { |
| 11 | + launch(Here) { // create new coroutine without an explicit threading policy |
| 12 | + delay(1000L) // non-blocking delay for 1 second |
| 13 | + println("World!") // print after delay |
| 14 | + } |
| 15 | + println("Hello,") // main function continues while coroutine is delayed |
| 16 | +} |
| 17 | +``` |
| 18 | + |
| 19 | +> You can get full code with imports [here](src/test/kotlin/examples/tutorial-example-1.kt) |
| 20 | +
|
| 21 | +Run this code: |
| 22 | + |
| 23 | +``` |
| 24 | +Hello! |
| 25 | +World! |
| 26 | +``` |
| 27 | + |
| 28 | +Essentially, coroutines are light-weight threads. You can achieve the same result replacing |
| 29 | +`launch(Here) { ... }` with `thread { ... }` and `delay(...)` with `Thread.sleep(...)`. Try it. |
| 30 | + |
| 31 | +If you start by replacing `launch(Here)` by `thread`, the compiler produces the following error: |
| 32 | + |
| 33 | +``` |
| 34 | +Error: Kotlin: Suspend functions are only allowed to be called from a coroutine or another suspend function |
| 35 | +``` |
| 36 | + |
| 37 | +That is because `delay` is a special _suspending function_ that does not block a thread, but _suspends_ |
| 38 | +coroutine and it can be only used from a coroutine. |
| 39 | + |
| 40 | +## Coroutines ARE light-weight |
| 41 | + |
| 42 | +Run the following code: |
| 43 | + |
| 44 | +```kotlin |
| 45 | +fun main(args: Array<String>) { |
| 46 | + repeat(100_000) { |
| 47 | + launch(Here) { // create new coroutine without an explicit threading policy |
| 48 | + delay(1000L) // non-blocking delay for 1 second |
| 49 | + print(".") // print one dot per coroutine |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +> You can get full code with imports [here](src/test/kotlin/examples/tutorial-example-2.kt) |
| 56 | +
|
| 57 | +It starts 100K coroutines and, after a second, each coroutine prints a dot. |
| 58 | +Now, try that with threads. What would happen? (Most likely your code will produce some sort of out-of-memory error) |
0 commit comments