guava-eventbus
Guide to Guava’s EventBus
1. Overview
2. Setup
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
The latest version can be found here.
3. Using the EventBus
3.1. Setup
We start by looking at the EventBus object. It can register listeners and post events. Using it is as simple as instantiating the class:
EventBus eventBus = new EventBus();
Guava library gives you the freedom of using the EventBus in any way that best suits your development needs.
3.2. Creating Listeners
We create a listener class that has handler methods to receive specific events. We annotate the handler methods with @Subscribe. The method accepts as an argument an object of the same type as the event being posted:
public class EventListener {
private static int eventsHandled;
@Subscribe
public void stringEvent(String event) {
eventsHandled++;
}
}
3.3. Registering Listeners
EventListener listener = new EventListener();
eventBus.register(listener);
3.4. Unregistering Listeners
eventBus.unregister(listener);
3.5. Posting Events
@Test
public void givenStringEvent_whenEventHandled_thenSuccess() {
eventBus.post("String Event");
assertEquals(1, listener.getEventsHandled());
}
3.6. Posting Custom Events
public class CustomEvent {
private String action;
// standard getters/setters and constructors
}
Adding a handler method in the EventListener class for that event:
@Subscribe
public void someCustomEvent(CustomEvent customEvent) {
eventsHandled++;
}
We can now post our custom event:
@Test
public void givenCustomEvent_whenEventHandled_thenSuccess() {
CustomEvent customEvent = new CustomEvent("Custom Event");
eventBus.post(customEvent);
assertEquals(1, listener.getEventsHandled());
}
4. Conclusion
You can find the complete source code and all code snippets for this article over on GitHub.