So is there an actual difference (well except the ...
# coroutines
g
So is there an actual difference (well except the fact of the obvious thats a different tool) to return a mutable state flow as a: • StateFlow • asLiveData() From experimenting today sounds like
mutableStateFlow.asLiveData()
is pretty much best of both worlds as you can have access to the operators privately while exposing a lifecycle aware state? Is there any huge pitfall I haven’t think of?
👍 1
w
I’d go further and ask if I can just not use live data and instead use
StateFlow
collected in e.g. fragment’s view lifecycle scope?
s
You can get rid of LiveData all together. You can expose your ViewModel’s (State)Flows as plain Flows to the UI (Activities/Fragments) and collect them in their
lifecycleScope
, even using the
whenStarted { … }
or
whenResumed { … }
constructs that make use of the Pausing Dispatcher.
g
Yes i know but is there any advantages of one approach to the other? Or is it preference?
s
Mindshare. If your team is familiar with LiveData, more than Flows, use LiveData. Also, if you use DataBinding, LiveData are a better fit (not sure if Flows are supported as well as LiveData by DataBinding….) But if you start fresh and Flows are familiar to you and your team, I suggest using Flow. One less type/class (LiveData) to deal with 🙂
g
Ok yeah that was what i was thinking!
i
For StateFlow, definitely recommend staying in the Flow world the entire way. For a non-state Flow, you'd probably want to wait for
shareIn
to land before swapping entirely away from using
asLiveData()
as without the
shareIn
you're going to lose the caching of the previous state. StateFlow obviously keeps it's current state all the time already
☝️ 4
5
👍 6
o
Also be aware that
StateFlow
conflates by structural equality, therefore if you want to expose for example a domain entity implementing
equals
in terms of its ID, then
StateFlow
will never emit updates. Discovered this recently and had to go back to
ConflatedBroadcastChannel
which conflates by referential equality.