Is this a bug in LiveData? Steps: 1. Call `liveD...
# android
a
Is this a bug in LiveData? Steps: 1. Call
liveData.postValue(StateOne)
2. Call
liveData.postValue(StateTwo)
Actual: The LiveData observer only receives
StateTwo
because inside
postValue
, while the
mPostValueRunnable
is being posted from the first call,
pendingData
gets replaced by the second call. Is that expected or should LiveData be posting two separate runnables, one by one?
i
It is expected in LiveData that you only get the latest state, yes
👍 1
a
I guess that's fair for mutually exclusive states where you'd want to ignore the result of the first one. Just strange because updating
liveData.value
is expected to deliver every state...right?
i
LiveData is for latest state only. If you
post
, you'll only get the latest
a
Thanks Ian. But when you set
liveData.value
, that will deliver every time, right? Or is that also subject to the same behaviour as
postValue
?
c
While it might emit values multiple times for
setValue()
, you shouldn’t write your code expecting that to happen. If you need to know the full history of events that are emitted, you should probably look into coroutine Channels or Flow instead, both of which can be tied into the
lifecycleScope
to achieve the same kind of app state guarantees that LiveData does
a
Thanks @Casey Brooks, I'll check out Flows with
lifecycleScope
. LiveData's been working well for the last year and a half with the app though. 🤷‍♂️
i
If an Observer sets the value, later Observers will get that new value and not the previous one
So certainly possible even without
postValue
But to Casey's point, you shouldn't ever be using LiveData in event like cases where you need every value. The last value should be the complete and updated state of the world
👍 1
a
Thanks for the clarification 🙂