Tuesday, December 15, 2015

Android -- Eventbus

/*
public class EventBus {

HashMap<String, List<Event>>

public void register(String eventName, Event event) {};
public void unregister(String eventName, Event event){};
public void postEvent(String eventName, Object Data){};

public interface Event {
  void onEvent(Object data);
}

}
*/

class EventBus {
  private Map<String, List<Event>> map;
  
  public EventListener() {
    map = new HashMap<String, List<Event>>();
  }
  
  public void register(String eventName, Event event) {
    if (map.containsKey(eventName)) {
      map.get(eventName).add(event);
    } else {
      List<Event> events = new ArrayList<Event>();
      events.add(event);
      map.put(eventName, events);
    }
  };
  
  public void unregister(String eventName, Event event) {
    if (map.containsKey(eventName)) {
      map.get(eventName).remove(event);
    }
  };

  public void postEvent(String eventName, Object data) {
if(map.containsKey(eventName)){
List<Event> events = map.get(eventName);
for(Event event : events){
event.doEvent(data);
}
}
 
/*
    Event event = new Event();
    event.doEvent(data);
    this.register(eventName, event);
    */
  };

class Event {
  private Object data;
  
  public void doEvent(Object data) {
    this.data = data;
  };

}

No comments:

Post a Comment