Search code examples
javafxobservableextractor

FXCollections, Callback<E, Observable[]> extractor for Sets?


I am aware of the factory method that takes an extractor as a parameter:

FXCollections.observableList(List<E> list, Callback<E, Observable[]> extractor)

Is there an equivalent for an ObservableSet?

If not, how can I achieve same/ similar functionality when I use an ObservableSet instead of an ObservableList?


Solution

  • There isn't. In fact, where ListChangeListener.Change has a wasUpdated() method, which returns true when the change is created because one of the properties specified in the extractor has changed, SetChangeListener.Change has no such method.

    If your set contains elements of type S, which has a property of type Property<T>, call it someProperty(), in which you are interested, you can do

    ChangeListener<T> listener = (obs, oldValue, newValue) -> { /* some code */ };
    
    ObservableSet<S> set = FXCollections.observableSet();
    set.addListener((Change<? extends S> c) -> {
        if (c.wasAdded()) {
            c.getElementAdded().someProperty().addListener(listener);
        }
        if (c.wasRemoved()) {
            c.getElementRemoved().someProperty().removeListener(listener);
        }
    });