blob: ab7899702004034dcc43a21138db578e9ae31ac7 [file] [log] [blame]
Roman Elizarovd4dcbe22017-02-22 09:57:46 +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
17// 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.select02
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030019
20import kotlinx.coroutines.experimental.*
21import kotlinx.coroutines.experimental.channels.*
22import kotlinx.coroutines.experimental.selects.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030023import kotlin.coroutines.experimental.*
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030024
25suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String =
26 select<String> {
27 a.onReceiveOrNull { value ->
28 if (value == null)
29 "Channel 'a' is closed"
30 else
31 "a -> '$value'"
32 }
33 b.onReceiveOrNull { value ->
34 if (value == null)
35 "Channel 'b' is closed"
36 else
37 "b -> '$value'"
38 }
39 }
40
41fun main(args: Array<String>) = runBlocking<Unit> {
42 // we are using the context of the main thread in this example for predictability ...
Roman Elizarov43e3af72017-07-21 16:01:31 +030043 val a = produce<String>(coroutineContext) {
Roman Elizarova84730b2017-02-22 11:58:50 +030044 repeat(4) { send("Hello $it") }
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030045 }
Roman Elizarov43e3af72017-07-21 16:01:31 +030046 val b = produce<String>(coroutineContext) {
Roman Elizarova84730b2017-02-22 11:58:50 +030047 repeat(4) { send("World $it") }
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030048 }
49 repeat(8) { // print first eight results
50 println(selectAorB(a, b))
51 }
Roman Elizarov8b38fa22017-09-27 17:44:31 +030052 coroutineContext.cancelChildren()
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030053}