Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +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 | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | a9687a3 | 2018-06-29 17:28:38 +0300 | [diff] [blame] | 6 | package kotlinx.coroutines.experimental.guide.select03 |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +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.channels.* |
| 10 | import kotlinx.coroutines.experimental.selects.* |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 11 | import kotlin.coroutines.experimental.* |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 12 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 13 | fun produceNumbers(context: CoroutineContext, side: SendChannel<Int>) = produce<Int>(context) { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 14 | for (num in 1..10) { // produce 10 numbers from 1 to 10 |
| 15 | delay(100) // every 100 ms |
| 16 | select<Unit> { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 17 | onSend(num) {} // Send to the primary channel |
| 18 | side.onSend(num) {} // or to the side channel |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 19 | } |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 24 | val side = Channel<Int>() // allocate side channel |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 25 | launch(coroutineContext) { // this is a very fast consumer for the side channel |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 26 | side.consumeEach { println("Side channel has $it") } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 27 | } |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 28 | produceNumbers(coroutineContext, side).consumeEach { |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 29 | println("Consuming $it") |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 30 | delay(250) // let us digest the consumed number properly, do not hurry |
| 31 | } |
| 32 | println("Done consuming") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 33 | coroutineContext.cancelChildren() |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 34 | } |