Is there an way to `select<T> { ... }` using...
# coroutines
j
Is there an way to
select<T> { ... }
using two
Flow
? I would like to choose between which ever returns a response first. One flow is a stream of data and the other is a StateFlow indicating the current connection state. If the connection state flow is
!= CONNECTED
I’d like my return an error, but if I get the data before the connection state is no longer
CONNECTED
, I’d like to return the data.
s
Since you want to collect the two flows concurrently, you'll need to
produce
them and then select between the resulting channels
j
I’m unfamiliar with the
produce
. Thank you for the suggestion.
s
I think for a flow it's
produceIn
, let me find the docs
z
I think you could also just merge the flows and operate on the result?
1
s
Was about to say, now I think about it, maybe there's a flow operator for this instead
j
The two flows return two different data types so I don’t think merge would work.
z
RxJava has an operator for this:
amb
. I'm not sure it exists for Flow Looks like nope.
j
So the recommended approach is
produceIn
?
z
I can't think of an easier way to do it
j
You’re suggestion of the merge could work if I add a map operator to my source flows and returned a sealed type. I will investigate both options. Thank you and @Sam for the suggestions. I have an idea of the path forward.
z
There's lots of articles about how to implement
amb
in flow (often renamed to something like "race", which makes much more sense). If you want to factor out your business logic a bit from the flow wiring you could do that.