Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX: Binding and weak listener

Tags:

java

javafx

From Javadoc for bind():

Note that JavaFX has all the bind calls implemented through weak listeners. This means the bound property can be garbage collected and stopped from being updated.

Now consider that I have two properties ObjectProperty<Foo> shortLived residing in ShortLivedObject and ObjectProperty<Foo> longLived residing in LongLivedObject.

I am binding them like this:

longLivedObject.longLivedProperty().bind(shortLivedObject.shortLivedProperty());

Because binding uses weak listener, so if shortLivedObject is garbage collected, shortLived property would be garbage collected as well. So, does that means that longLived property is still bound, but it will never be updated? Does that leave longLived property in a bound state (making further binding impossible), but does nothing?

like image 834
Jai Avatar asked Nov 21 '25 16:11

Jai


1 Answers

So, does that means that longLived property is still bound, but it will never be updated?

Assuming that the shortLivedProperty has been garbage collected, the shortLivedProperty will never be invalidated again. As a result, the listener of the longLived will never be called and updated again.

Does that leave longLived property in a bound state (making further binding impossible), but does nothing?

You should always be able to bind a property to a new observable regardless of the binding state as the old observable property will be removed/unbound for you:

public void bind(final ObservableValue<? extends T> newObservable) {
    if (newObservable == null) {
        throw new NullPointerException("Cannot bind to null");
    }

    if (!newObservable.equals(this.observable)) {
        unbind();
        observable = newObservable;
        if (listener == null) {
            listener = new Listener(this);
        }
        observable.addListener(listener);
        markInvalid();
    }
}
like image 137
shaka-b Avatar answered Nov 24 '25 05:11

shaka-b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!