Coroutines: Given an input, I want to launch two c...
# announcements
o
Coroutines: Given an input, I want to launch two coroutines to find a solution for that input. I know how to launch these two in parallel, but how do I make the coroutine that finds the solution first return the earliest, so that the root suspending function doesn't have to wait on the other coroutine when the solution is already been found. So basically, instead of
awaitAll()
I need something like
awaitAllFirstFinished()
m
you may have better luck in the #coroutines channel, though my guess is
select()
will be what you want: https://kotlinlang.org/docs/reference/coroutines/select-expression.html
a
You can write an adapter that waits for an upstream deferred, cancels the other jobs and then pushes the result to a shared CompletableDeferred, which you then wait on. Something very roughly like:
Copy code
fun adapt(out: CompletableDeferred<T>, allJobs: Collection<Jobs>) = launch {
  val result = deferred.await()
  out.complete(result)
  allJobs.forEach { it.cancel() }
}

val out = CompletableDeferred<T>()
allDeferreds.map { adapt(out, allDeferreds) }.joinAll()
error handling and correct scoping to avoid cancellation causing armageddon is left out ­čśë using
select
is probably simpler, though