Android Event Bus with Example

Akshay Rana GuJJar
3 min readSep 10, 2020
Android Event Bus with Example

EventBus is the number 1 event library for android and java. EventBus uses the publisher and subscriber pattern for loose coupling which means the possibility of errors will be less. EventBus simplifies the communication between different components for example communications between different levels of activities or even services. You need very less or no setup to use EventBus in your existing project.

EventBus provides a convenient annotation-based API which makes it fast and the performance is increased. EventBus is used by many popular apps, apps which has 1 billion-plus download which shows how EventBus popular.

In this tutorial, we will see how we can get started using EventBus in an android project. Before jumping in the code let’s see what we will be going to make. To better understanding EventBus we will make an app that allows us to add items to the cart and show the total count of the items. See below how our app will work.

EventBus App example

Let’s get started.

Add EventBus Dependency in Android Studio

First, we need to add EventBus Dependency in the project. Open your build.gradle and add the dependency.

Hit the sync button and move to the next step.

Make a POJO class for EventBus

The next step is to make a Java object class to pass in the EevntBus Subscribe method and to be used later.

For our example app, we will make a class with the name of CartEvent.java with a string field for cart items.

See the below code for better understanding.

Move to the next step.

See also: Should Know Libraries for Android Developers

Make UI for the App

In the first activity, we have a textview to show the total count of the cart item.

And a button to open second activity to add items in the cart.

See the below code to understand.

Now make the second activity to show the items list and add a method for the button click.

We made simple cart items. We add 3 items but in the real world application, you should use recyclerview or any other view to make a list of items.

Here is the second activity XML code.

In the above code, we have added the onClick attribute and pass the addItemToCart method name.

And made the appropriate method in the second activity java.

Now implement EventBus in the project.

Let’s make the subscriber and in the subscriber method, we will add items to the list.

See below to understand.

Make Subscribe Method of EventBus to update Cart

--

--