Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | // This file was automatically generated from coroutines-guide-reactive.md by Knit tool. Do not edit. |
Roman Elizarov | a9687a3 | 2018-06-29 17:28:38 +0300 | [diff] [blame] | 6 | package kotlinx.coroutines.experimental.rx2.guide.basic02 |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 7 | |
Roman Elizarov | 95981f3 | 2017-03-17 18:12:04 +0300 | [diff] [blame] | 8 | import kotlinx.coroutines.experimental.* |
| 9 | import kotlinx.coroutines.experimental.reactive.* |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 10 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 11 | |
| 12 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 13 | // create a publisher that produces numbers from 1 to 3 with 200ms delays between them |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 14 | val source = publish<Int>(coroutineContext) { |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 15 | // ^^^^^^^ <--- Difference from the previous examples is here |
| 16 | println("Begin") // mark the beginning of this coroutine in output |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 17 | for (x in 1..3) { |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 18 | delay(200) // wait for 200ms |
| 19 | send(x) // send number x to the channel |
| 20 | } |
| 21 | } |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 22 | // print elements from the source |
| 23 | println("Elements:") |
| 24 | source.consumeEach { // consume elements from it |
| 25 | println(it) |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 26 | } |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 27 | // print elements from the source AGAIN |
| 28 | println("Again:") |
| 29 | source.consumeEach { // consume elements from it |
| 30 | println(it) |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 31 | } |
| 32 | } |