1. Overview
Guava library provides the EventBus which allows publish-subscribe communication between components. In this tutorial, we will look at how to use some of the features of the EventBus.
2. Setup
To start we add the Google Guava library dependency in the pom.xml:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>21.0</version> </dependency>
3. Using the EventBus
Let’s start by using a simple example.
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
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
If for any reason we want to unregister a class from the EventBus, that can also be easily done:
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()); }
3.7. Handling an Unsubscribed Event
We are provided with a DeadEvent class that allows us to handle any events that have no listeners. We can add a method to handle the DeadEvent class:
@Subscribe public void handleDeadEvent(DeadEvent deadEvent) { eventsHandled++; }
4. Conclusion
In this tutorial, we used a simple example as a guide on how to use the Guava EventBus.
You can find the complete source code and all code snippets for this article over on GitHub.