Search code examples
androidobservableobservers

Observable Notify Multiple variables change


How I can Notify on Multiple variables update?

Is there any method to detect and separatenotifyObservers?

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

}

How can detect witch variable has changed?


Solution

  • How about wrapping animalId and weight inside another type: for example AnimalProperty

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

    so your code would look like this:

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

    then in the Observer's update(...) method switch on the propertyName to know which property is updated