Created
December 12, 2017 10:40
-
-
Save piyush-malaviya/828644b4f14d127e3a0f5980901aa016 to your computer and use it in GitHub Desktop.
NotificationCenter class like ios
This file contains hidden or 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
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); | |
} | |
}); | |
**/ |
This file contains hidden or 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
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