The more you work with coroutines, the more you'll get used to await results. At some point, you'll start sending deferred values over channels.
We'll start by creating 10 async tasks. The first will delay for a long time, and others we delay for a short time:
val elements = 10
val deferredChannel = Channel<Deferred<Int>>(elements)
launch(CommonPool) {
repeat(elements) { i ->
println("$i sent")
deferredChannel.send(async {
delay(if (i == 0) 1000 else 10)
i
})
}
}
We'll put all those results into a buffered channel.
Now we can read from this channel, and be using a second select block, and await the results:
val time = measureTimeMillis {
repeat(elements) {
val result = select<Int> {
deferredChannel.onReceive {
select {
...