https://kotlinlang.org logo
#coroutines
Title
# coroutines
g

George Theocharis

08/04/2020, 3:47 PM
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

wasyl

08/04/2020, 3:50 PM
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

streetsofboston

08/04/2020, 3:51 PM
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

George Theocharis

08/04/2020, 3:55 PM
Yes i know but is there any advantages of one approach to the other? Or is it preference?
s

streetsofboston

08/04/2020, 3:58 PM
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

George Theocharis

08/04/2020, 3:58 PM
Ok yeah that was what i was thinking!
i

Ian Lake

08/04/2020, 4:00 PM
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

okarm

08/04/2020, 4:23 PM
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.
3 Views