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:

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:

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:

This test can not be simpler 🙂 We create EventBus instance and listener class instance, then register listener and post new event. And of course this test passes 🙂

MultiListener

Guava also allows to create listener that is reacting for many different events. We just need to annotate many methods with @Subscribe and that’s all:

and a simple example:

We don’t have to implement multiple interfaces, Guava provides a nice and clean solution with one annotation.

Beyond the basics

Now let’s analyze some more interesting features of EventBus.

Dead Event

First unusal thing is a DeadEvent class, predefined event which is fired when we’ve posted any type of event but no one was there to receive it. To see how it works let’s create listener waiting for dead events:

and test case showing how it works:

So if there was no listener waiting for event which was posted, EventBus fires DeadEvent so we could do something or at least add info to log files to be aware that such situation occured.

Events hierarchy

Another interesting feature is that listeners can leverage existing events hierarchy. So if Listener A is waiting for events A, and event A has a subclass named B, this listener will receive both type of events: A and B. This can be presented with short example. Let’s create two listeners, one listening for Number class events and second one for Integer (which in case you didn’t know is a subclass of Number 🙂 ):

And a test method showing this feature:

In this method we see that first event (new Integer(100)) is received by both listeners, but second one (new Long(200L)) reaches only NumberListener as Integer one isn’t created for this type of events.

This feature can be used to create more generic listeners listening for a broader range of events and more detailed ones for specific purposes.

Summary

In this post I’ve presented some features of less known fragment of Guava Library, an EventBus class. It’s a very elegant and easy to apply solution when you need to listen for some events and publish them without creating sophisticated classes and interfaces hierarchy. And finally, this class is next good reason to add Guava to dependencies in your project 🙂