Notify LiveData observers when nested properties change

Viewed 3314

Say my LiveData looks like this LiveData<List<Dog>> dogsLiveData = ...

When I make a change to a property of a Dog object, I want the observer of the LiveData to be notified. How do I do that?

public void doChange(){
   List<Dog> dogs = dogsLiveData.value;
   Dog d = dogs.get(1);
   d.setLegs(5); //I want this to trigger notification. How?
}

(leg changed from 4 to 5 in the example)

2 Answers

You may have a MutableLiveData instead of LiveData to be able to set new values. According to Android Documentation , LiveData is immutable and MutableLiveData extends LiveData and is mutable.

So you need to change from LiveData<List<Dog>> to MutableLiveData<List<Dog>>

Also, in your ViewModel, create a method for the list observable:

 public LiveData<List<Dog>> getDogsObservable() {
        if (dogsLiveData == null) {
            dogsLiveData = new MutableLiveData<List<Dog>>();
        }
        return dogsLiveData;
 }

And finally on your MainActivity or whatever activity which holds the ViewModel add this piece of code:

viewModel.getDogsObservable().observe(context, dogs -> { //Java 8 Lambda
    if (dogs != null) {
       //Do whatever you want with you dogs list
    }
}

The only way is to re-assign the live data value, it won't trigger on changes to the list's elements.

public void doChange(){
   List<Dog> dogs = dogsLiveData.value;
   Dog d = dogs.get(1);
   d.setLegs(5);
   dogsLiveData.value = dogs
}
Related