xref: /aosp_15_r20/external/kotlinx.coroutines/kotlinx-coroutines-core/jvm/test/guide/example-select-04.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.exampleSelect04
3 
4 import kotlinx.coroutines.*
5 import kotlinx.coroutines.selects.*
6 import java.util.*
7 
8 fun CoroutineScope.asyncString(time: Int) = async {
9     delay(time.toLong())
10     "Waited for $time ms"
11 }
12 
asyncStringsListnull13 fun CoroutineScope.asyncStringsList(): List<Deferred<String>> {
14     val random = Random(3)
15     return List(12) { asyncString(random.nextInt(1000)) }
16 }
17 
<lambda>null18 fun main() = runBlocking<Unit> {
19     val list = asyncStringsList()
20     val result = select<String> {
21         list.withIndex().forEach { (index, deferred) ->
22             deferred.onAwait { answer ->
23                 "Deferred $index produced answer '$answer'"
24             }
25         }
26     }
27     println(result)
28     val countActive = list.count { it.isActive }
29     println("$countActive coroutines are still active")
30 }
31