Skip to content
Evgeniy Goroshkin edited this page Sep 13, 2015 · 2 revisions

Event System for java

What inside

  • Event & SimpleEvent - this is an event object, that will be generate (fire) event signal.
  • IEventListener - listener, that will be subscribed to event and receive signal.
  • EventSystem - optional static class, that helps un-subscribe all events when object become to die (need to call it manually).

How to use

Best practice is make event object 'public final', and so create it at instance creation time. This allow to subscribe at any time.

public final Event<MyEventArgs> eventSomethingHappen = EventSystem.newEvent(this);

If you want to use EventSystem, object must implement IWithEvents. This interface is empty, but it unify all objects with events.

Then you may subscribe event from anywhere your instance available:

myObj.eventSomethingHappen.subscribe(listener);
...
private final IEventListener<MyEventArgs> listenerForSomethingHappen = new IEventListener<MyEventArgs>() {
@Override
public void onReceived(Object sender, MyEventArgs args) {
// extract data from args if needed
// do some action
// unsubscribe if needed
}
};

When object become to die, and you create event via EventSystem, you may unsubscribe from all listeners by call one line of code:

EventSystem.remove(this); // remove from event system, not from memory

When closing app you may unsubscribe all app events:

EventSystem.removeAllObjects();

Clone this wiki locally