首页 > 解决方案 > Observable Notify 多个变量变化

问题描述

如何通知多个变量更新?

有什么方法可以检测和分离notifyObservers吗?

public class AnimalWeightObservable extends Observable {

    public long animalId;

    public long weigh;

    public long getAnimalId() {
        return animalId;
    }

    public AnimalWeightObservable setAnimalId(long animalId) {
        this.animalId = animalId;
        this.setChanged();
        this.notifyObservers(animalId);
        return this;
    }

    public long getWeigh() {
        return weigh;
    }

    public AnimalWeightObservable setWeigh(long weigh) {
        this.weigh = weigh;
        this.setChanged();
        this.notifyObservers(weigh);
        return this;
    }

}

如何检测女巫变量是否发生了变化?

标签: androidobservableobservers

解决方案


如何包装animalIdweight内部另一种类型:例如AnimalProperty

class AnimalProperty<T> {
    String propertyName;
    T property;

    AnimalProperty(String name, T property) {
        this.propertyName = name;
        this.property = property;
    }
}

所以你的代码看起来像这样:

public class AnimalWeightObservable extends Observable {

    public AnimalProperty animalId;

    public AnimalProperty weigh;

    //...
    //...

    public AnimalWeightObservable setWeigh(AnimalProperty weigh) {
        this.weigh = weigh;
        this.setChanged();
        this.notifyObservers(weigh);
        return this;
    }
}

然后在Observer'supdate(...)方法中打开 就propertyName知道哪个属性被更新了


推荐阅读