guigarage / ObserverPattern

Basic Java observer API
Apache License 2.0
7 stars 7 forks source link

addAndFire support #3

Open hendrikebbers opened 7 years ago

hendrikebbers commented 7 years ago

One functionality that I currently miss in mostly all change listener APIs that I have seen is a methods that fires the listener directly after the listener was added. Here is an example in Swift code:

class DynamicString {

  func bind(listener: Listener?) {
    self.listener = listener
  }

  func bindAndFire(listener: Listener?) {
   bind(listener)
    listener?(value)
  }
  ...
}

Currently you write code like this most of the time:

public Constructor(Property property) {
   property.onChanged(e -> updateMeBasedOnPropertyValue(e.getNewValue()));  
   updateMeBasedOnPropertyValue(property.getValue());
}

I think missing the second line in the method is a common bug. With the new Concept you could write:

public Constructor(Property property) {
   property.onChangedAndFire(e -> updateMeBasedOnPropertyValue(e.getNewValue()));
}

The method name onChangedAndFire is really horrible and must change :) But I like the concept.