August 12, 2009

Observer Pattern revised: The EventBus

The EventBus library is a convenient realization of the observer pattern. It works perfectly to supplement the implemention of MVC logic (model-view-controller) in event-driven UIs such as Swing. The library is similiar to the JMS API and it's published under the Apache License 2.0.
The Event Bus is a single-process publish/subscribe event routing library, with Swing extensions. The EventBus is fully-functional, with very good API documentation and test coverage (80+%). It has been deployed in many production environments, including financial, engineering and scientific applications.



Let's take a look at a simple example:

Events can be easily spread across the application by publishing to the bus. You can use any class you want as an event:
EventBus.publish(new MyEvent());

There are many ways to listen on events from the bus, e.g. you can consume the fired event via an annotated method in some of your controllers (the C of MVC):
@EventSubscriber(eventClass = MyEvent.class)
protected void onMyCustomEvent(MyEvent event) {
// do something   
}

Additionally each annotated subscriber has to be registered to the library:
AnnotationProcessor.process(obj);

The invocation of EventBus#publish() will result in the invocation of each subscribing method for the particular type of event.

https://eventbus.dev.java.net/

1 comments:

Andy said...

I just got into a huge debate with my coworker over Observers vs. Event Buses...

So if you have multiple models, and you want them to have distinct views and controllers, how would you handle events? You could pass the view or the model in a special event class, but there wouldn't be a way to ensure that a controller only receives events
from its view or model, would there?