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
Sam
07/31/2024, 7:49 AM
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
Davio
07/31/2024, 8:04 AM
That does not cancel other tasks after the fastest one succeeds
s
Sam
07/31/2024, 8:05 AM
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
Davio
07/31/2024, 8:18 AM
Ah right, there was something weird in my test, now it works, thanks!