Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Base class for Java Observable
public abstract class BaseObservable<LISTENER_CLASS> {
private final Object MONITOR = new Object();
private final Set<LISTENER_CLASS> mListeners = new HashSet<>();
public void registerListener(LISTENER_CLASS listener) {
synchronized (MONITOR) {
boolean hadNoListeners = mListeners.size() == 0;
mListeners.add(listener);
if (hadNoListeners && mListeners.size() == 1) {
onFirstListenerRegistered();
}
}
}
public void unregisterListener(LISTENER_CLASS listener) {
synchronized (MONITOR) {
boolean hadOneListener = mListeners.size() == 1;
mListeners.remove(listener);
if (hadOneListener && mListeners.size() == 0) {
onLastListenerUnregistered();
}
}
}
protected Set<LISTENER_CLASS> getListeners() {
synchronized (MONITOR) {
return Collections.unmodifiableSet(new HashSet<>(mListeners));
}
}
protected void onFirstListenerRegistered() {
}
protected void onLastListenerUnregistered() {
}
}
@maciej-kaznowski

This comment has been minimized.

Copy link

@maciej-kaznowski maciej-kaznowski commented Aug 15, 2019

https://gist.github.com/techyourchance/6602815188294c1c58779d3e8d16f12b#file-baseobservable-java-L10
Could instead do:

boolean added = mListeners.add(listener);
           if (hadNoListeners && added) {
               onFirstListenerRegistered();
           }

https://gist.github.com/techyourchance/6602815188294c1c58779d3e8d16f12b#file-baseobservable-java-L20
Similiarly:

boolean removed = mListeners.remove(listener);
            if (hadOneListener && removed) {
                onLastListenerUnregistered();
            }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.