blob: 72fc837880e862afd267fe05a23a6e85fab92ec5 [file] [log] [blame]
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001/*
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03002 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03003 */
4
5// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
Roman Elizarova9687a32018-06-29 17:28:38 +03006package kotlinx.coroutines.experimental.guide.select03
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03007
Roman Elizarov95981f32017-03-17 18:12:04 +03008import kotlinx.coroutines.experimental.*
9import kotlinx.coroutines.experimental.channels.*
10import kotlinx.coroutines.experimental.selects.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030011import kotlin.coroutines.experimental.*
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030012
Roman Elizarov8b38fa22017-09-27 17:44:31 +030013fun produceNumbers(context: CoroutineContext, side: SendChannel<Int>) = produce<Int>(context) {
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030014 for (num in 1..10) { // produce 10 numbers from 1 to 10
15 delay(100) // every 100 ms
16 select<Unit> {
Roman Elizarova84730b2017-02-22 11:58:50 +030017 onSend(num) {} // Send to the primary channel
18 side.onSend(num) {} // or to the side channel
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030019 }
20 }
21}
22
23fun main(args: Array<String>) = runBlocking<Unit> {
24 val side = Channel<Int>() // allocate side channel
Roman Elizarov43e3af72017-07-21 16:01:31 +030025 launch(coroutineContext) { // this is a very fast consumer for the side channel
Roman Elizarov86349be2017-03-17 16:47:37 +030026 side.consumeEach { println("Side channel has $it") }
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030027 }
Roman Elizarov8b38fa22017-09-27 17:44:31 +030028 produceNumbers(coroutineContext, side).consumeEach {
Roman Elizarov86349be2017-03-17 16:47:37 +030029 println("Consuming $it")
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030030 delay(250) // let us digest the consumed number properly, do not hurry
31 }
32 println("Done consuming")
Roman Elizarov8b38fa22017-09-27 17:44:31 +030033 coroutineContext.cancelChildren()
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030034}