Deferred channel
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 { it.onAwait{ it } } } } println(result) } } println("Took ${time}ms")
Note that the resulting time is of the slowest task:
Took 1010ms
You can also use onAwait()
as...