r/android_devs • u/leggo_tech • May 23 '20
Coding StateFlow vs LiveData
I read this article
https://medium.com/scalereal/stateflow-end-of-livedata-a473094229b3
I don't really understand the difference between stateflow and livedata.
Can someone correct me if I'm wrong:
StateFlow has more operators because it's just a Flowable (also something idk) but that means it's already a bit more like Rx than just a LiveData thing?
StateFlow can actually have a default value set it seems like. I don't believe LiveData actually has this ability.
LiveData.value needs to have !! or ? because value is nullable, but with StateFlow the value can be non null?
1
u/MrXplicit Aug 04 '20
So is there a pitfall on doing val state = mutableStateFlow.asLiveData() ?
Seems like the best of both worlds.
13
u/Zhuinden EpicPandaForce @ SO May 23 '20
The major difference is that
LiveDataonly comes withobserveandobserveForeverout of the box, andMediatorLiveDatais a means of composing multiple LiveData in various ways.LiveData is readable and writeable only on UI thread (
postValuemoves the write to UI thread), butFlowis Kotlin Coroutine stuff (not Flowable in this case, not Rx).Although my understanding of this is not yet complete, I need to see where
SharedFlowgoes, and a sample on how to wrap reactive event streams.Still, the idea is that a
StateFlowcannot be created without an initial value, this avoids null propagation.If you check my LiveData helper here, you see I am returning
LiveData<Tuple3<T1?, T2?, T3?>>- a bunch of nulls!How much nicer would it be if you only received values on the call site when all values are available? Alas, that is not safe with LiveData. But it will be with StateFlow.
Also you won't have to write this
combinehelper yourself. Flows can also more easily swap threads in a coroutine context, rather than being confined to UI thread (although I hear theliveData {coroutine builder already lets you "venture off to different threads" through theemit()suspending function).