Guide to Guava’s EventBus in Java

Setup

EventBus eventBus = new EventBus();

Creating Listeners

public class EventListener {
 
    private static int eventsHandled;
 
    @Subscribe
    public void stringEvent(String event) {
        eventsHandled++;
    }
}

Registering Listeners

EventListener listener = new EventListener();
eventBus.register(listener);

Unregistering Listeners

eventBus.unregister(listener);

Posting Events

@Test
public void givenStringEvent_whenEventHandled_thenSuccess() {
    eventBus.post("String Event");
    assertEquals(1, listener.getEventsHandled());
}

Posting Custom Events

public class CustomEvent {
    private String action;
 
    // standard getters/setters and constructors
}
@Subscribe
public void someCustomEvent(CustomEvent customEvent) {
    eventsHandled++;
}
@Test
public void givenCustomEvent_whenEventHandled_thenSuccess() {
    CustomEvent customEvent = new CustomEvent("Custom Event");
    eventBus.post(customEvent);
 
    assertEquals(1, listener.getEventsHandled());
}

Handling an Unsubscribed Event

@Subscribe
public void handleDeadEvent(DeadEvent deadEvent) {
    eventsHandled++;
}

References
http://www.baeldung.com/guava-eventbus

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.