GumTree event bus is a powerful API for simplifying the use of listener pattern in your code. Listener pattern is sometimes considered to be difficult to maintain because programmers need to include many addXXListener() / removeXXXListener() in the API. Event bus is introduce to solve this coupling problem, together with providing a more centralised way of managing all events in the system. GumTree event bus is based on the well known publish-subscribe pattern.
Let's say we have a publisher which can produce an event upon state change. For each state change, it will pass an event called StateChangedEvent to all of its subscribers.
- Step 1:
StateChangedEvent implementation (must implement from org.gumtree.core.eventbus.IEvent):
- Step 3:
Now, we implement a subscriber to catch this event:
- Step 3:
We subscribe this handler to the event bus:You may also use the following API if you are only interest in a particular producer:
- Step 4:
Publish event in an asynchronised wayTo send event in a synchronised way, use sendEvent().
Limitation:
- Dose not support removal of subscriber on bundle removal from OSGi. This can be solved using the whiteboard pattern or event admin API from OSGi.
- Each event bus has only one thread in its threading pool. If there is a long running task inside a handleEvent() method, all event dispatching will be delayed. For any mission critical event handling, consider creating your own private event bus rather than using the global one from the GumTree platform.
References:
- Event-driven programming from wikipedia
- Event Bus is an example of Pub-sub Event broadcasting mechanism in Java
