Introduction
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.
How to use the Event Bus
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().
Event Filtering
Many event bus implementations provide filtering mechanism to avoid unrelated events passing to the subscribers. For example, OSGi uses the topic string matching as the event filter. In GumTree, you can do this by subclassing the event handler with org.gumtree.core.eventbus.IFilteredEventHandler. For example,
Of course, if the filtering is not in use, the event bus will remain as a broadcast publisher.
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
- Message Bus a.k.a. Event Bus
- Event Bus is an example of Pub-sub Event broadcasting mechanism in Java
- E4/Event Processing discusses the event bus proposal for Eclipse 4.0
