Last active
December 28, 2021 13:38
-
-
Save techyourchance/6602815188294c1c58779d3e8d16f12b to your computer and use it in GitHub Desktop.
Base class for Java Observable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/techyourchance/6602815188294c1c58779d3e8d16f12b#file-baseobservable-java-L10
Could instead do:
https://gist.github.com/techyourchance/6602815188294c1c58779d3e8d16f12b#file-baseobservable-java-L20
Similiarly: