With knockout.js computed observables it is possible to define a JavaScript observable that depends on other observables, using a functional expression, e.g.
var computedObservable = ko.computed(function(){
return firtName() + lastName();
});
If one of the referenced observables (e.g. firstName) changes, the computed observable is automatically updated. The referenced observables are defined by the given functional expression and do not have to be explicitly specified.
How can I implement something similar in Java?
(Well, there are JavaFx Bindings, but they require the explicit registration of the referenced properties/observables.)
I distinguish two cases:
a) The given lambda expression is analyzed with Java to automatically find out which referenced observables have to be considered. (The referenced observables might reference further observables in a dependency chain.) Expected example code:
ComputedObservable<String> computedObservable = new ComputedObservable<>(() -> {
return firstName.get() + lastName.get();
});
b) I have to manually register each referenced observable to be able to observe them. I would like to avoid this case. With other words I do not want to have code like
ComputedObservable<String> computedObservable = new CoputedObservable<>();
computedObservable.registerReference(firstName);
computedObservable.registerReference(lastName);
computedObservable.setExpresion(() -> {
return firstName.get() + lastName.get();
});
or (using JavaFx Bindings)
DoubleBinding db = new DoubleBinding() {
{
super.bind(a, b, c, d);
}
@Override
protected double computeValue() {
return (a.get() * b.get()) + (c.get() * d.get());
}
};
Is case a) possible at all and if yes, is there an existing Java implementation/library for doing so?
Edit: There is another strategy:
c) Use specialized operators to define the functional expression. Those operators implicitly register the referenced observables. So there is no need for an extra manual registration step. (The functional expression will be limited to the available operators and advanced functionality might require to implement new helping operators.)
StringBinding fullName = firstName.concat(secondName);
DoubleBinding result = a.multiply(b).add(c.multiply(d));
Related questions: