You might have missed it, but there were some significant new features added to JavaFX in the 19 and 21 releases. These all relate to Observables
, and make creating Bindings
and Listeners
easier to use.
I don’t think enough noise was made about these when they came out, and I totally missed them until a little while ago. I spent some time experimenting with them, looking at the source code, and then wrote an article to explain just about everything you need to know:
https://www.pragmaticcoding.ca/javafx/subscribe_and_map
First, we now have some methods to create Subscriptions
on Observables
, and these are way easier to use than ChangeListener
and InvalidationListener
. Basically, Subscriptions
are wrappers around the Listeners
, so the same notification mechanism is used “under the hood”, but they are easier to declare and manage.
Secondly, a new method has been added, ObseravbleValue.map()
. This is super cool, and allows all kinds of conversions and calculations to be baked into any Binding with only one Observable
dependency.
Finally, we now have ObservableValue.flatMap()
which allows you to create bindings that reach through composed objects with Property fields. This is going to be massively useful in those cases where you need to bind the Property
of a Property
and have it re-evaluate if either the wrapper Property
or the contained Property
change.
Even if you don’t normally read my articles, you should have a look at this. You’ll probably want to upgrade all of your projects to JFX 21 right away - I know I do.