Here I have written a MutableLiveList<T> class that is intended to replace MutableLiveData<MutableList<T>> in my project. This is working fine till now. But if multiple modifications are done to the list when that activity is in inactive state, then only the last modification to that list will trigger adapter notify methods. In this case I don't know will the app crash. So I needed to mimic that situation exactly. When the screen rotates, activity gets destroyed and recreated. But I don't know how to add items to that list between that interval. Anyone please help me. Or tell me a better way to do it.

1

There are 1 answers

4
cactustictacs On BEST ANSWER

You could add them in the activity's onDestroy callback function. At that point the activity's Lifecycle object is either in the CREATED or DESTROYED state:

A chart of how a Lifecycle object's states change with app lifecycle events

Point is it's not in the STARTED state at that point, and:

LiveData considers an observer, which is represented by the Observer class, to be in an active state if its lifecycle is in the STARTED or RESUMED state. LiveData only notifies active observers about updates. Inactive observers registered to watch LiveData objects aren't notified about changes.

So by the time you're in onDestroy, any observer using that activity's Lifecycle won't see any updates from the LiveData. So you should be able to add values to the LiveData without getting notified.


By the way, that "only notified of the last value" update is by design:

Generally, LiveData delivers updates only when data changes, and only to active observers. An exception to this behavior is that observers also receive an update when they change from an inactive to an active state. Furthermore, if the observer changes from inactive to active a second time, it only receives an update if the value has changed since the last time it became active.

So if the data goes A, B, C while the observer is inactive, it won't be notified of those values. When it goes from inactive to inactive, it'll get the most recent value, C. It doesn't save a history of all the values an observer has missed