I would like to “`select` ” between multiple `asyn...
# coroutines
e
I would like to “`select` ” between multiple
async
operations but I want to select the first one that succeeds OR fail only after everyone fails. Seems current select with
onAwait
will fail when any of the operations fail, is there a way to achieve the other behavior?
r
I'm not sure if there is a more idiomatic way to do it but here is what I came up with some noodling.
👍 1
s
Sounds like a race. What about this one?
Copy code
suspend fun <T> race(vararg tasks: suspend () -> T): T =
  channelFlow { tasks.forEach { launch { send(it()) } } }.first()
r
To make sure errors don't crash the whole thing, you'll need to wrap each coroutine in a
runCatching
e
Yeah went with channel at last but it feels like this should be a configuration of select
r
I could be wrong but select is has been in the linux kernel for reading from multiple streams of io without blocking on a specific one. Which is why they probably used channels as it is the closes analog. https://www.man7.org/linux/man-pages/man2/select.2.html
This api was vital for being able to have an event bus for handling IO.