https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

Marcelo Velloso

12/21/2018, 2:40 PM
I have a question on coroutines. I want to launch two coroutines asynchronously and wait on whichever completes first, is this possible? The context here is that two separate server calls can be made independently and if either returns an error I want to cancel the remaining coroutine and error out.
s

sashjakk

12/21/2018, 2:51 PM
I think this is possible with
select
m

Marcelo Velloso

12/21/2018, 4:35 PM
Thanks, I looked into select. I think I may have to use something like runBlocking instead because if the first thread succeeds I want to get the response from the second thread. I suppose I could always cancel the second thread of the first thread fails.
b

bdawg.io

12/21/2018, 5:06 PM
This is what structured concurrency does. Wrap the two in a
coroutineScope
and if you launch the two jobs using
async
, one of them failing automatically cancels the other
m

Marcelo Velloso

12/21/2018, 6:12 PM
This is exactly what I was looking for, thanks!
When I run normally I see both threads output one after the other, if they were running asynchronously wouldn't the logs interleave? I do call an await on one before the other but I'm not sure how else to do it when using async.
b

bdawg.io

12/21/2018, 9:43 PM
await just suspends until the specific Deferred is completed (regardless if the other one completes first or not). It doesn't necessarily mean the one you awaited first will finish first
4 Views