Skip to content

Instantly share code, notes, and snippets.

@cbedoy
Created April 10, 2015 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbedoy/10a6da428a2c03cd15fd to your computer and use it in GitHub Desktop.
Save cbedoy/10a6da428a2c03cd15fd to your computer and use it in GitHub Desktop.
Provider notifications from observers
import java.util.ArrayList;
import java.util.HashMap;
public class NotificationCenter {
private static NotificationCenter mInstance;
private final HashMap<Integer, ArrayList<NotificationListener>> mListeners;
private NotificationCenter() {
mListeners = new HashMap<Integer, ArrayList<NotificationListener>>();
}
public static NotificationCenter getInstance() {
if (mInstance == null) {
mInstance = new NotificationCenter();
}
return mInstance;
}
public static void clearInstance() {
mInstance = null;
}
public void addListener(Integer type, NotificationListener listener) {
synchronized (mListeners) {
ArrayList<NotificationListener> listeners = mListeners.get(type);
if (listeners == null) {
listeners = new ArrayList<NotificationListener>();
}
if (!listeners.contains(listener)) {
listeners.add(listener);
}
mListeners.put(type, listeners);
}
}
public void removeListener(Integer type, NotificationListener listener) {
synchronized (mListeners) {
ArrayList<NotificationListener> listeners = mListeners.get(type);
if (listeners != null && listeners.contains(listener)) {
listeners.remove(listener);
}
if (listeners != null && listeners.size() > 0) {
mListeners.put(type, listeners);
} else {
mListeners.remove(type);
}
}
}
public void postNotification(Integer type, Object... notification) {
synchronized (mListeners) {
ArrayList<NotificationListener> listeners = mListeners.get(type);
if (listeners != null && listeners.size() > 0) {
for (NotificationListener listener : listeners) {
listener.didReceivedNotification(type, notification);
}
}
}
}
public interface NotificationListener {
public abstract void didReceivedNotification(Integer type, Object... args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment