Lets say I have a sealed class `A` with 2 subclass...
# coroutines
f
Lets say I have a sealed class
A
with 2 subclasses
B
and
C
. Can I combine a
Flow<B>
and a
Flow<C>
to a
Flow<A>
?
m
combine(flowA, flowB) { some logic here }
🎯 1
l
@Florian Did you fire up a Google search with the obvious keywords before asking? If not, can you guess what would be the right keywords?
f
I already tried
combine
but I don't see how I can return a Flow of the superclass
m
combine<A>(flowB, flowC)
well, I think the kotlin compiler inference can resolve it for you
f
but I have to return a single value from the block
l
Now I understand what you can better. It seems you want to merge these two flows, am I right?
f
yes
I can only return something like a
Pair
from
combine
but I want a Flow that emits each value separately as its supertype
l
So the right keywords are "kotlin flow merge", not combine as combine is designed to combine the last value of each flow.
👍 1
f
Thanks, but this was not an obvious keyword
l
Yep, I understand how
combine
was more natural to think of
f
but thank you very much for your help
l
Did you find the right operator to use?
f
merge seems to work
l
Yep, looks to be just what you need 🙂
Before asking here, did you look at the KDoc of
combine
? I'm aksing to understand your thought process, and see if the doc should mention the
merge
operator to help folks in the future.
f
I already knew combine, I'm using it in my project
I thought I'll have to use combine but I didn't know with what transform block
I will google more thoroughly next time
m
you can learn a lot with the Rx diagrams that explain the work of each operator...
the concept of Flow transformation operators are pretty the same thing
f
thank you
m
oh, I didn't realize there is one for Flows already: https://flowmarbles.com/
👍 4
f
wow 🤩 I'm gonna bookmark that right away
1
looks like
combine
was actually the correct operator, because with
merge
I don't get all the values into a single Flow
I just get separate emits from both Flows
instead I now merge the 2 lists inside the combine operator like this:
Copy code
val combinedChatFlow: Flow<List<Chat>> = combine(directChatsFlow, groupChatsFlow) { directChats, groupChats ->
    directChats + groupChats
}
m
this is the difference between the two operators