Hi all, I have a question / use case for racing: I...
# arrow
d
Hi all, I have a question / use case for racing: I want to get a (hopefully) non-null result and have some ways to get it, how do I combine racing with each of my function calls returning null if the result can not be obtained / found in that function? So I would like to have the first non-null result of these functions and once one returns non-null, cancel the rest
s
Copy code
fun <T> race(vararg tasks: suspend () -> T) = channelFlow {
  for (task in tasks) launch { send(task()) }
}

race(task1, task2).filterNotNull().first()
thank you color 1
d
That does not cancel other tasks after the fastest one succeeds
s
In fact, it does, because
first()
is a terminal operator that will end the flow. The channel flow has its own coroutine scope which is cancelled when the flow terminates.
d
Ah right, there was something weird in my test, now it works, thanks!
🎉 1
🐕 1