xref: /aosp_15_r20/external/kotlinx.coroutines/kotlinx-coroutines-core/jvm/test/guide/example-select-02.kt (revision 7a7160fed73afa6648ef8aa100d4a336fe921d9a)

<lambda>null1 // This file was automatically generated from select-expression.md by Knit tool. Do not edit.
2 package kotlinx.coroutines.guide.exampleSelect02
3 
4 import kotlinx.coroutines.*
5 import kotlinx.coroutines.channels.*
6 import kotlinx.coroutines.selects.*
7 
8 suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String =
9     select<String> {
10         a.onReceiveCatching { it ->
11             val value = it.getOrNull()
12             if (value != null) {
13                 "a -> '$value'"
14             } else {
15                 "Channel 'a' is closed"
16             }
17         }
18         b.onReceiveCatching { it ->
19             val value = it.getOrNull()
20             if (value != null) {
21                 "b -> '$value'"
22             } else {
23                 "Channel 'b' is closed"
24             }
25         }
26     }
27 
<lambda>null28 fun main() = runBlocking<Unit> {
29     val a = produce<String> {
30         repeat(4) { send("Hello $it") }
31     }
32     val b = produce<String> {
33         repeat(4) { send("World $it") }
34     }
35     repeat(8) { // print first eight results
36         println(selectAorB(a, b))
37     }
38     coroutineContext.cancelChildren()
39 }
40