嵌套属性更改时通知LiveData观察者

时间:2019-06-19 00:47:58

标签: android android-architecture-components android-livedata

说我的LiveData像这样LiveData<List<Dog>> dogsLiveData = ...

当我更改Dog对象的属性时,我希望通知LiveData的观察者。我该怎么办?

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

(在示例中,腿从4变为5)

2 个答案:

答案 0 :(得分:0)

唯一的方法是重新分配实时数据值,它不会在列表元素更改时触发。

isinstance(obj, Derived)

答案 1 :(得分:0)

您可能拥有MutableLiveData而不是LiveData才能设置新值。 According to Android Documentation,LiveData是不可变的,而MutableLiveData扩展了LiveData并且是可变的。

因此,您需要从LiveData<List<Dog>>更改为MutableLiveData<List<Dog>>

此外,在您的ViewModel中,为可观察到的列表创建一个方法:

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

最后在MainActivity或任何包含ViewModel的活动上添加以下代码:

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