Skip to content

Instantly share code, notes, and snippets.

@hpstuff
Created March 29, 2017 09:16
Show Gist options
  • Save hpstuff/26c0e3d3995ea7190eede0d7567de612 to your computer and use it in GitHub Desktop.
Save hpstuff/26c0e3d3995ea7190eede0d7567de612 to your computer and use it in GitHub Desktop.
NotificationCenter
import java.util.ArrayList;
import java.util.HashMap;
public class NotificationCenter {
//static reference for singleton
private static NotificationCenter _instance;
private HashMap<String, ArrayList<Runnable>> registredObjects;
//default c'tor for singleton
private NotificationCenter(){
registredObjects = new HashMap<String, ArrayList<Runnable>>();
}
//returning the reference
public static synchronized NotificationCenter defaultCenter(){
if(_instance == null)
_instance = new NotificationCenter();
return _instance;
}
public synchronized void addFucntionForNotification(String notificationName, Runnable r){
ArrayList<Runnable> list = registredObjects.get(notificationName);
if(list == null) {
list = new ArrayList<Runnable>();
registredObjects.put(notificationName, list);
}
list.add(r);
}
public synchronized void removeFucntionForNotification(String notificationName, Runnable r){
ArrayList<Runnable> list = registredObjects.get(notificationName);
if(list != null) {
list.remove(r);
}
}
public synchronized void postNotification(String notificationName){
ArrayList<Runnable> list = registredObjects.get(notificationName);
if(list != null) {
for(Runnable r: list)
r.run();
}
}
}
@hpstuff
Copy link
Author

hpstuff commented Mar 29, 2017

android NotificationCenter.defaultCenter().postNotification("test")
swift 2 NSNotificationCenter.defaultCenter().postNotificationName("test")
swift 3 NotificationCenter.default.post("test")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment