Event Bus - Decouple Your Classes Easily

Very often you might hear that it is good to have classes highly cohesive & loosely coupled. For many people, it may mean something a little bit different. So more important than just hearing to the slogan, is to have practical examples of what it actually means. In order to achieve loose coupling you should consider event bus at the beginning.


Why do I actually want to use have loose coupling? Imagine a scenario when you display same data in multiple forms: as chart, as table or verbally in natural language. And let’s make the data changes over time. In order to keep all dependent components up to date you would need to maintain list of it and send fresh data directly to everyone. It’s going to be hard, when number of them changes over time (while project grows) and it makes them depend on source of data.

On the other hand you could use event bus, as a source of changes, also known as events.

How to use event bus? Let’s take a look at the simple example below.

public void init() {
    EventBus eventBus = new EventBus();

    Chart dataChart = new Chart();
    Table dataTable = new Table();
    TextPanel textPanel = new TextPanel();

    eventBus.register(dataChart);
    eventBus.register(dataTable);
    eventBus.register(textPanel);

    eventBus.post(new DataUpdateEvent(dataResource.fetchCurrent()));
}

class Chart {
    @Subscribe
    public void onNewData(DataUpdateEvent event) {
        // ...
    }
}

Simple as that. What do you gain by that?

  1. You separate data displaying classes (Chart, Table and TextPanel) from underlying data resource. You can easily change the source of data, without making even a change in those classes.
  2. They can be easily tested. You don’t have to pass EventBus via constructor or setter. The only thing you have to do is to create a new instance of e.g. Chart and call public method onNewData.
  3. Adding new sources of data is simple. You just have to wire it to eventBus. Sources of data don’t have to know anything about recipients. That way, your code is open for extensions and closed for modifications.
  4. If data dependents can also modify data, it’s easy to propagate changes to the rest. Just post an update to eventBus. Specific classes are unaware of recipients and doesn’t have to worry about them.

If you haven’t use the tool, give it a try. For sure it will make your code coupled less.

---

There also other benefits of Event Bus. In a single class, you can subscribe for multiple objects. The whole mechanism is type safe, so you always get what you were expecting. And it’s developed by Google.

If you want to learn more, you can find official docs here.