Hello is there any way to run two coroutines in pa...
# coroutines
p
Hello is there any way to run two coroutines in parallel and then return the first result that finishes first? I've thought to use
Job
and then if the first finishes first cancel the second
Job
to stop doing the work, also I think the way to do it is using
launch{}
right? Instead of
async {}
p
Can you provide a pseudo example how does `select`works?
I've found this but don't know if it's what I want because I guess it waits for all coroutines to finish https://stackoverflow.com/questions/69045114/return-a-specific-value-only-of-the-faster-coroutine
s
p
Copy code
suspend fun getFaster(): Int = coroutineScope {
    select<Int> {
        async { getFromServer() }.onAwait { it }
        async { getFromDB() }.onAwait { it }
    }.also {
        coroutineContext.cancelChildren()
    }
}
This would work?
s
Arrow Fx offers some syntactic sugar on top of KotlinX.
p
I'm not using Arrow Simon, otherwise I'd ask for Arrow stuff, I'm using Coroutines.
s
The Github Arrow link I shared is the piece of code you're looking for. You can just copy-paste it.
n
merge(::foo.asFlow(), ::bar.asFlow()).first()
If you have suspend methods foo and bar