Search code examples
javacollectionsobservers

Give ListChangeListener initial state


I want to observe an ObservableList that is modified by completely seperate code. My problem is that I do not just want my ListChangeListener to be invoked when the list changes (when I attach my listener the list may already contain elements), but I also want the initial state to be passed to the listener.

Obviously I could do the following:

list.addListener(this::listenerMethod);
listenerMethod(fakeChange);

But with this approach any item that is added between the two method calls would be handled twice, which is not ideal.

When the order is reversed:

listenerMethod(fakeChange);
list.addListener(this::listenerMethod);

The second approach would totally ignore any elements added between the two method calls.

What would be the best way of dealing with such a situation?


Solution

  • It seems that what you should care about is knowing when your listener is invoked for the first time to process any pre-invocation elements.

    In your case since the listener may never be invoked what you need to change is when and how you verify the list initial state. Since the change listener is your implementation, I would pass the list to the listener constructor and process the initial state at that point. If the listener is never invoked, you are covered.