Skip to content

Instantly share code, notes, and snippets.

@piyush-malaviya
Created December 12, 2017 10:40
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 piyush-malaviya/828644b4f14d127e3a0f5980901aa016 to your computer and use it in GitHub Desktop.
Save piyush-malaviya/828644b4f14d127e3a0f5980901aa016 to your computer and use it in GitHub Desktop.
NotificationCenter class like ios
import java.util.HashMap;
import java.util.Observer;
public final class NotificationCenter {
private static NotificationCenter instance;
private final HashMap<String, NotificationObservable> observables;
private NotificationCenter() {
observables = new HashMap<>();
}
public static synchronized NotificationCenter getInstance() {
if (instance == null) {
instance = new NotificationCenter();
}
return instance;
}
public void addObserver(String notification, Observer observer) {
NotificationObservable observable = observables.get(notification);
if (observable == null) {
observable = new NotificationObservable();
observables.put(notification, observable);
}
observable.addObserver(observer);
}
public void removeObserver(String notification, Observer observer) {
NotificationObservable observable = observables.get(notification);
if (observable != null) {
observable.deleteObserver(observer);
}
}
public void postNotification(String notification, Object object) {
NotificationObservable observable = observables.get(notification);
if (observable != null) {
observable.notifyObservers(object);
}
}
public int getObserverCount(String notification) {
NotificationObservable observable = observables.get(notification);
if (observable != null) {
return observable.countObservers();
}
return 0;
}
}
/**
Post notification
NotificationCenter.getInstance().postNotification("your_key, object);
Notification Observer
NotificationCenter.getInstance().addObserver("your key", new Observer() {
@Override
public void update(Observable o, Object arg) {
// if you want to remove when task complete then
NotificationCenter.getInstance().removeObserver("your key", this);
}
});
**/
import java.util.Observable;
class NotificationObservable extends Observable {
public void notifyObservers(Object data) {
setChanged();
super.notifyObservers(data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment