blob: 40407e807933b75aa8e437f45748d8f948cf97b2 [file] [log] [blame]
Roman Elizarovf16fd272017-02-07 11:26:00 +03001/*
2 * Copyright 2016-2017 JetBrains s.r.o.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Roman Elizarovb7721cf2017-02-03 19:23:08 +030017// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
Roman Elizarova9687a32018-06-29 17:28:38 +030018package kotlinx.coroutines.experimental.guide.channel05
Roman Elizarovb7721cf2017-02-03 19:23:08 +030019
Roman Elizarovcaaed5c2017-02-15 17:56:02 +030020import kotlinx.coroutines.experimental.*
21import kotlinx.coroutines.experimental.channels.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030022import kotlin.coroutines.experimental.*
Roman Elizarovb7721cf2017-02-03 19:23:08 +030023
Roman Elizarova5e653f2017-02-13 13:49:55 +030024fun numbersFrom(context: CoroutineContext, start: Int) = produce<Int>(context) {
Roman Elizarovb7721cf2017-02-03 19:23:08 +030025 var x = start
26 while (true) send(x++) // infinite stream of integers from start
27}
28
Roman Elizarova5e653f2017-02-13 13:49:55 +030029fun filter(context: CoroutineContext, numbers: ReceiveChannel<Int>, prime: Int) = produce<Int>(context) {
Roman Elizarovb7721cf2017-02-03 19:23:08 +030030 for (x in numbers) if (x % prime != 0) send(x)
31}
32
33fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov43e3af72017-07-21 16:01:31 +030034 var cur = numbersFrom(coroutineContext, 2)
Roman Elizarovb7721cf2017-02-03 19:23:08 +030035 for (i in 1..10) {
36 val prime = cur.receive()
37 println(prime)
Roman Elizarov43e3af72017-07-21 16:01:31 +030038 cur = filter(coroutineContext, cur, prime)
Roman Elizarovb7721cf2017-02-03 19:23:08 +030039 }
Roman Elizarov8b38fa22017-09-27 17:44:31 +030040 coroutineContext.cancelChildren() // cancel all children to let main finish
Roman Elizarovb7721cf2017-02-03 19:23:08 +030041}