可观察通知多个变量更改

时间:2019-02-03 13:17:23

标签: android observable observers

如何通知多个变量更新?

有什么方法可以检测并分离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;
    }

}

如何可以检测女巫变量已经改变?

1 个答案:

答案 0 :(得分:1)

如何将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的{​​{1}}方法中打开update(...),以了解哪个属性已更新