简体   繁体   中英

JavaFX: Binding and weak listener

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?

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM