5

I tried different collections under different conditions but all changes that I was able to receive were Permutation, Add, Removed and Replace changes.

In what conditions does update change emerge? What base class, what stored class and what operations is needed to produce such event?

ayvango
  • 5,867
  • 3
  • 34
  • 73

1 Answers1

9

To generate an update event, you must create an ObservableList with an extractor.

The extractor is a function mapping each element in the list to an array of Observables. If any of those Observables change (while the element is still in the list), then the list will receive an update event.

For example, given a Person class:

public class Person {
    private final StringProperty name = new SimpleStringProperty();

    public Person(String name) {
        nameProperty().set(name);
    }

    public StringProperty nameProperty() {
        return name ;
    }
    public final String getName() {
        return nameProperty().get();
    }
    public final void setName(String name) {
        nameProperty().set(name);
    }
}

if you create an observable list as

ObservableList<Person> people = FXCollections.observableArrayList(person -> 
    new Observable[] {person.nameProperty()} );

and register a listener

people.addListener((Change<? extends Person> change) -> {
    while (change.next()) {
        if (change.wasAdded()) {
            System.out.println("Add");
        }
        if (change.wasUpdated()) {
            System.out.println("Update");
        }
    }
});

Then the following will show an update event:

Person person = new Person("Jacob Smith");
people.add(person);
person.setName("Isabella Johnson");
James_D
  • 201,275
  • 16
  • 291
  • 322
  • Is it possible to observe ordinary objects that have no fields, as `StringProperty`? – ilw Feb 16 '23 at 21:53
  • @ilw No, that is not possible. To observe changes to a field, there needs to be a mechanism coded for notification to happen. `StringProperty` and similar classes are a highly-efficient implementation of that. You could, of course, write your own mechanism from scratch, but at best you would just be re-creating something that already exists (so you’re not actually avoiding using the property mechanism), and at worst it would be far less efficient than the library implementation. – James_D Feb 17 '23 at 13:15