简体   繁体   中英

Notify LiveData observers when nested properties change

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)

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
}

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
    }
}

Drove an explanation to another query, and it's functioning nicely for my case. You can have a look at this explanation https://stackoverflow.com/a/73706683/4676291

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM