Google Guava in version number 10 introduced new package eventbus with a few very interesting classes to deal with listener (or publisher – subscriber) use case. Below I present my short introduction to EventBus class and its family.
Basics
To listen to some events we need a listener class. Such class created in google-guava-way doesn’t have to implement any particular interface or extend any specified class. It can be any class with just one required element: a method marked with @Subscribe annotation:
public class EventListener {
public int lastMessage = 0;
@Subscribe
public void listen(OurTestEvent event) {
lastMessage = event.getMessage();
}
public int getLastMessage() {
return lastMessage;
}
}
lastMessage property is used in tests below to check if events were received successfully.
And of course we need an event class to send it around:
public class OurTestEvent {
private final int message;
public OurTestEvent(int message) {
this.message = message;
}
public int getMessage() {
return message;
}
}
How it works
The best way to show something in action is to write some tests, so let’s see how simple usage of EventBus looks like:


