xref: /aosp_15_r20/external/kotlinx.coroutines/kotlinx-coroutines-core/jvm/test/guide/example-select-03.kt (revision 7a7160fed73afa6648ef8aa100d4a336fe921d9a)
1 // This file was automatically generated from select-expression.md by Knit tool. Do not edit.
2 package kotlinx.coroutines.guide.exampleSelect03
3 
4 import kotlinx.coroutines.*
5 import kotlinx.coroutines.channels.*
6 import kotlinx.coroutines.selects.*
7 
<lambda>null8 fun CoroutineScope.produceNumbers(side: SendChannel<Int>) = produce<Int> {
9     for (num in 1..10) { // produce 10 numbers from 1 to 10
10         delay(100) // every 100 ms
11         select<Unit> {
12             onSend(num) {} // Send to the primary channel
13             side.onSend(num) {} // or to the side channel
14         }
15     }
16 }
17 
<lambda>null18 fun main() = runBlocking<Unit> {
19     val side = Channel<Int>() // allocate side channel
20     launch { // this is a very fast consumer for the side channel
21         side.consumeEach { println("Side channel has $it") }
22     }
23     produceNumbers(side).consumeEach {
24         println("Consuming $it")
25         delay(250) // let us digest the consumed number properly, do not hurry
26     }
27     println("Done consuming")
28     coroutineContext.cancelChildren()
29 }
30