How to wait for the first of multiple Defereds to ...
# coroutines
p
How to wait for the first of multiple Defereds to finish? I think I can add
invokeOnCompletion
to each and cancel the rest of them when the first one completes, but maybe there's some built-in way?
s
Copy code
suspend fun <T> race(vararg jobs: Deferred<T>): T = try {
    select { jobs.forEach { job -> job.onAwait { it } } }
} finally {
    jobs.forEach { it.cancelAndJoin() }
}
☝️ this is my go-to snippet that I use in my projects
I think there are also some built-in race functions in #arrow, if you’re using that
p
@Sam looks nice, thanks!