Skip to content

Instantly share code, notes, and snippets.

@techyourchance
Last active December 28, 2021 13:38
Show Gist options
  • Save techyourchance/6602815188294c1c58779d3e8d16f12b to your computer and use it in GitHub Desktop.
Save techyourchance/6602815188294c1c58779d3e8d16f12b to your computer and use it in GitHub Desktop.
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
Copy link

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