The Observable<T> interface represents a reactive, stateful object that can be watched for changes. It provides a consistent and flexible API for building reactive UIs, data flows, and dynamic logic in applications.
Observables are designed to be either immutable or mutable, with support for compound states that automatically derive values from other observables. It includes built-in support for list-based observables, mapped observables, and reactive recomposition through dependency tracking.
This system is designed to be lightweight, composable, and extensible.
Usage
@Test
void example() {
MutableObservable<Integer> num = Observable.mutable(0);
Observable<Boolean> isEven = num.map(n -> n % 2 == 0);
Observable<String> parity = Observable.compound(num, isEven)
.map(args -> args.arg0() + ": " + args.arg1());
assertEquals("0: true", parity.get());
num.set(9); // Flag isEven and parity as dirty but don't recompute yet
assertEquals("9: false", parity.get());
num.set(42); // Flag isEven and parity as dirty but don't recompute yet
assertEquals("42: true", parity.get());
num.set(21); // Flag isEven and parity as dirty but don't recompute yet
num.set(42); // Flag isEven and parity as dirty but don't recompute yet
assertEquals("42: true", parity.get()); // output "42: true" but didn't need to recompute
// the final piece of the puzzle: if num reaches 69, we want to shut down the JVM
WatcherManager watcherManager = new WatcherManager();
num.lazyWatch(watcherManager, value -> {
if (value == 69) {
System.exit(69);
}
});
// In order to trigger the watching function, we need to call the heartbeat method
// If the value of num is 69, the JVM will shut down
// Right now it's not, we don't want to destroy our CI
watcherManager.heartbeat();
}