https://kotlinlang.org logo
Title
p

Pablo

08/25/2022, 10:13 AM
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

Pablo

08/25/2022, 10:15 AM
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

simon.vergauwen

08/25/2022, 10:19 AM
p

Pablo

08/25/2022, 10:19 AM
suspend fun getFaster(): Int = coroutineScope {
    select<Int> {
        async { getFromServer() }.onAwait { it }
        async { getFromDB() }.onAwait { it }
    }.also {
        coroutineContext.cancelChildren()
    }
}
This would work?
s

simon.vergauwen

08/25/2022, 10:19 AM
Arrow Fx offers some syntactic sugar on top of KotlinX.
p

Pablo

08/25/2022, 10:22 AM
I'm not using Arrow Simon, otherwise I'd ask for Arrow stuff, I'm using Coroutines.
s

simon.vergauwen

08/25/2022, 10:23 AM
The Github Arrow link I shared is the piece of code you're looking for. You can just copy-paste it.
n

Nick Allen

08/26/2022, 3:32 AM
merge(::foo.asFlow(), ::bar.asFlow()).first()
If you have suspend methods foo and bar