I have a question on coroutines. I want to launch ...
# coroutines
m
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
I think this is possible with
select
m
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
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
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
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