xref: /aosp_15_r20/external/kotlinx.coroutines/kotlinx-coroutines-core/jvm/test/guide/example-select-01.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.exampleSelect01
3 
4 import kotlinx.coroutines.*
5 import kotlinx.coroutines.channels.*
6 import kotlinx.coroutines.selects.*
7 
8 fun CoroutineScope.fizz() = produce<String> {
9     while (true) { // sends "Fizz" every 500 ms
10         delay(500)
11         send("Fizz")
12     }
13 }
14 
<lambda>null15 fun CoroutineScope.buzz() = produce<String> {
16     while (true) { // sends "Buzz!" every 1000 ms
17         delay(1000)
18         send("Buzz!")
19     }
20 }
21 
selectFizzBuzznull22 suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
23     select<Unit> { // <Unit> means that this select expression does not produce any result
24         fizz.onReceive { value ->  // this is the first select clause
25             println("fizz -> '$value'")
26         }
27         buzz.onReceive { value ->  // this is the second select clause
28             println("buzz -> '$value'")
29         }
30     }
31 }
32 
<lambda>null33 fun main() = runBlocking<Unit> {
34     val fizz = fizz()
35     val buzz = buzz()
36     repeat(7) {
37         selectFizzBuzz(fizz, buzz)
38     }
39     coroutineContext.cancelChildren() // cancel fizz & buzz coroutines
40 }
41