louiscad
12/26/2018, 5:45 PMsuspend fun <T> List<Deferred<T>>.race(): T = coroutineScope {
val winningValue = CompletableDeferred<T>()
this@race.forEach { racer ->
launch {
val winningCandidate = racer.await()
this@race.forEach { if (it != racer) racer.cancel() }
winningValue.complete(winningCandidate)
}
}
winningValue.await()
}
If you can think of a better solution, please post the snippet in this thread 🙂