问题
I have an ObservableList that doesn't only trigger the registered ListChangeListeners when elements are added or removed, but also when specific Observable attributes within these elements are changed, e.g. a list of persons and when a person's adress changes, the ListChangeListeners fire. How can I edit the adress of multiple people and have the Listeners only fire once for all changes together?
回答1:
ObservableList
does not provide this functionality by default. If you extend ModifiableObservableList though, you could make it's beginChange()
and endChange()
functionality accessible to external code.
You need to be careful though that this class is used correctly. If you do not do the same number of beginChange
and endChange
calls, the listener may not receive any updates at all.
The following code does not contain any implementation regarding update changes. I'll leave this up to you. You'll need to use nextUpdate
between calls of beginChange
and endChange
. You may need to add additional functionality to the doXyz
methods to add listeners, if you want that the extractor functionality.
public class BulkEditObservableList<T> extends ModifiableObservableListBase<T> {
private final List<T> backingList;
public BulkEditObservableList(List<T> backingList) {
if (backingList == null) {
throw new IllegalArgumentException();
}
this.backingList = backingList;
}
public BulkEditObservableList() {
this(new ArrayList<>());
}
@Override
public T get(int index) {
return backingList.get(index);
}
@Override
public int size() {
return backingList.size();
}
@Override
protected void doAdd(int index, T element) {
backingList.add(index, element);
}
@Override
protected T doSet(int index, T element) {
return backingList.set(index, element);
}
@Override
protected T doRemove(int index) {
return backingList.remove(index);
}
public void beginBulkChange() {
beginChange();
}
public void endBulkChange() {
endChange();
}
}
Usage example
BulkEditObservableList<Integer> intList = new BulkEditObservableList<>();
intList.addListener((Observable o) -> System.out.println(o));
intList.add(1);
intList.beginBulkChange();
intList.add(2);
intList.add(3);
intList.add(0, 0);
System.out.println("after multi add");
intList.endBulkChange();
Output
[1]
after multi add
[0, 1, 2, 3]
来源:https://stackoverflow.com/questions/59324227/edit-multiple-elements-in-observablelist-and-only-fire-change-listeners-after-la