【问题标题】:Observable Notify Multiple variables changeObservable Notify 多个变量变化
【发布时间】:2019-06-27 10:24:35
【问题描述】:

如何通知多个变量更新?

有没有办法检测和分离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;
    }

}

如何检测女巫变量的变化?

【问题讨论】:

标签: android observable observers


【解决方案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;
    }
}

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

【讨论】:

  • 这是一个绝妙的主意,我在想 ** this.notifyObservers("ID"+id)**,但不是一个干净的代码,非常感谢
  • 不客气。 P.S,考虑将您的财产设为私有 :)
  • 那是因为 ORM ;)
猜你喜欢
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-04
相关资源
最近更新 更多