Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
8290040: Provide simplified deterministic way to manage listeners
Reviewed-by: nlisker, angorya, kcr, mstrauss
- Loading branch information
Showing
3 changed files
with
400 additions
and
2 deletions.
There are no files selected for viewing
67 changes: 67 additions & 0 deletions
67
modules/javafx.base/src/main/java/com/sun/javafx/binding/ConditionalBinding.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
package com.sun.javafx.binding; | ||
|
||
import java.util.Objects; | ||
|
||
import javafx.beans.value.ObservableValue; | ||
|
||
public class ConditionalBinding<T> extends LazyObjectBinding<T> { | ||
|
||
private final ObservableValue<T> source; | ||
private final ObservableValue<Boolean> nonNullCondition; | ||
|
||
private Subscription subscription; | ||
|
||
public ConditionalBinding(ObservableValue<T> source, ObservableValue<Boolean> condition) { | ||
this.source = Objects.requireNonNull(source, "source cannot be null"); | ||
this.nonNullCondition = Objects.requireNonNull(condition, "condition cannot be null").orElse(false); | ||
|
||
// condition is always observed and never unsubscribed | ||
Subscription.subscribe(nonNullCondition, current -> { | ||
invalidate(); | ||
|
||
if (!current) { | ||
getValue(); | ||
} | ||
}); | ||
} | ||
|
||
/** | ||
* This binding is valid whenever it is observed, or it is currently inactive. | ||
* When inactive, the binding has the value of its source at the time it became | ||
* inactive. | ||
*/ | ||
@Override | ||
protected boolean allowValidation() { | ||
return super.allowValidation() || !isActive(); | ||
} | ||
|
||
@Override | ||
protected T computeValue() { | ||
if (isObserved() && isActive()) { | ||
if (subscription == null) { | ||
subscription = Subscription.subscribeInvalidations(source, this::invalidate); | ||
} | ||
} | ||
else { | ||
unsubscribe(); | ||
} | ||
|
||
return source.getValue(); | ||
} | ||
|
||
@Override | ||
protected Subscription observeSources() { | ||
return this::unsubscribe; | ||
} | ||
|
||
private boolean isActive() { | ||
return nonNullCondition.getValue(); | ||
} | ||
|
||
private void unsubscribe() { | ||
if (subscription != null) { | ||
subscription.unsubscribe(); | ||
subscription = null; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.