Aw: Easier handling of ObservableList/Set/Map change events
Marius Hanl
mariushanl at web.de
Mon Oct 25 22:23:27 UTC 2021
I like this idea.
Pretty sure some listener I wrote won't handle a permutation correctly.
I may have one question: Is there something that needs to be done in
case of an update (wasUpdated)?
-- Marius
Gesendet: Mittwoch, 20. Oktober 2021 um 21:07 Uhr
Von: "Michael Strauß" <michaelstrau2 at gmail.com>
An: "openjfx-dev at openjdk.java.net List" <openjfx-dev at openjdk.java.net>
Betreff: Easier handling of ObservableList/Set/Map change events
I'd like to gauge interest on a small feature addition for JavaFX
collections.
ObservableList (and similarly, ObservableSet/ObservableMap) allows
developers to register ListChangeListeners to observe changes to the
list. In some cases, these changes are applied to another list or
projected into a different form.
Implementing ListChangeListener correctly is quite tricky, especially
if the ObservableList implementation also fires "replace" and
"permutate" events. As a result, it is very easy to implement this
interface wrongly, which often goes undetected when the implementation
is only tested against basic operations like "add" and "remove".
Maybe we could make it easier for developers to get it right more of
the time, by offering pre-built adapters for ListChangeListener,
SetChangeListener and MapChangeListener.
Here's what that could look like:
public abstract class ListChangeListenerAdapter<E> implements
ListChangeListener<E> {
// Basic methods
public abstract void onAdded(int index, E element);
public abstract void onRemoved(int index);
// Optional methods
public void onAdded(int index, List<? extends E> elements);
public void onRemoved(int from, int to);
public void onReplaced(int index, E element);
public void onUpdated(int index, E element);
}
An implementation of this adapter must at the very least implement the
basic `onAdded` and `onRemoved` methods. The adapter will then
correctly map all other change events ("replace" and "permutate") to
these methods. All adapter methods will always be called in exactly
the right order, such that they always refer to the current state of
the list.
An adapter implementation can improve performance characteristics by
overriding the optional `onAdded`, `onRemoved` and `onReplaced`
methods (which map to `addAll`, `remove` and `set` of the List
interface). Optional methods are implemented by default to throw a
private exception in ListChangeListenerAdapter, which is used to
discover whether the methods are overridden and should be called
instead of the basic methods.
More information about the openjfx-dev
mailing list