Hi all, out of curiosity, I was thinking about a parallel fallback construction, how would you implement the following use case (with or without Arrow):
• In parallel, start N computations
• Have a preference / priority for the result of the first computation
• If the first computation fails or returns no result (null), use the result of the second (fallback) computation
• If the first computation succeeds, cancel the second computation and use the value of the first computation
a
Alejandro Serrano.Mena
10/09/2024, 7:56 AM
you speak about N computations, but then you speak about "first" and "second". Do you mean here "first" as "the first one to finish" (then raceN is your friend) or literally there's a distinguished first one (in that case using
await
on the first one, and only if that one is
null
awaiting the rest would work)
d
Davio
10/09/2024, 8:04 AM
Ah yes, I talked about N, but that is a theoretical thing, in my example I just assume 1 regular computation and 1 fallback computation, but started at the same time (to save on total time in case the fallback was needed)
Davio
10/09/2024, 8:07 AM
So I guess I don't need Arrow for this, but can simply do
Copy code
runBlocking {
val regularJob = async<String?> { "hello" }
val fallbackJob = async { "world" }
val result = regularJob.await() ?: fallbackJob.await()
}