blob: 9b3ce1cd99e11508bb6649eb4405e27f21650aa1 [file] [log] [blame]
Roman Elizarovf16fd272017-02-07 11:26:00 +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 Elizarovf16fd272017-02-07 11:26:00 +03003 */
4
Roman Elizarovb7721cf2017-02-03 19:23:08 +03005// 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.channel05
Roman Elizarovb7721cf2017-02-03 19:23:08 +03007
Roman Elizarovcaaed5c2017-02-15 17:56:02 +03008import kotlinx.coroutines.experimental.*
9import kotlinx.coroutines.experimental.channels.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030010import kotlin.coroutines.experimental.*
Roman Elizarovb7721cf2017-02-03 19:23:08 +030011
Roman Elizarova5e653f2017-02-13 13:49:55 +030012fun numbersFrom(context: CoroutineContext, start: Int) = produce<Int>(context) {
Roman Elizarovb7721cf2017-02-03 19:23:08 +030013 var x = start
14 while (true) send(x++) // infinite stream of integers from start
15}
16
Roman Elizarova5e653f2017-02-13 13:49:55 +030017fun filter(context: CoroutineContext, numbers: ReceiveChannel<Int>, prime: Int) = produce<Int>(context) {
Roman Elizarovb7721cf2017-02-03 19:23:08 +030018 for (x in numbers) if (x % prime != 0) send(x)
19}
20
21fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov43e3af72017-07-21 16:01:31 +030022 var cur = numbersFrom(coroutineContext, 2)
Roman Elizarovb7721cf2017-02-03 19:23:08 +030023 for (i in 1..10) {
24 val prime = cur.receive()
25 println(prime)
Roman Elizarov43e3af72017-07-21 16:01:31 +030026 cur = filter(coroutineContext, cur, prime)
Roman Elizarovb7721cf2017-02-03 19:23:08 +030027 }
Roman Elizarov8b38fa22017-09-27 17:44:31 +030028 coroutineContext.cancelChildren() // cancel all children to let main finish
Roman Elizarovb7721cf2017-02-03 19:23:08 +030029}