EventBus Library In Android
Building an Android application that has various dynamic segments speaking with one another can get repetitive. To save time, developers often end up with tightly coupled components in their apps like Interfaces or directly calling an object’s function.
EventBus is a popular open-source library that was created to solve this problem using the publisher/subscriber pattern.
Using the EventBus library, you can pass messages from one class to one or more classes in just a few lines of code.

Source : GreenRobot library
Methods of EventBus :
- register : To register your component to subscribe to events on the bus.
- unregister : To stop receiving events of the bus.
- post : To publish your event on the bus.
Add EventBus to your project
1 |
compile 'de.greenrobot:eventbus:3.0.0' |
Register your component to receive events
1 2 |
EventBus bus = EventBus.getDefault(); bus.register(this); |
Every class that intends to receive events from the event bus should contain an onEvent method. The name of this method is important, because the EventBus library uses the Java Reflection API to access this method. It has a single parameter that refers to the event.
1 2 3 4 5 |
@Subscribe public void onEvent(String message) { Log.i("message", message); } |
Create an Event
1 2 |
EventBus bus=EventBus.getDefault(); bus.post("Pass Message here."); |
Pass Object in EventBus
Registering your component will be same, only change you need to do is in your onEvent() and pass your object while creating event.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class PersonClass { String name; public PersonClass(String message) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
change parameter in onEvent()
1 2 3 4 5 |
@Subscribe public void onEvent(PersonClass person) { Log.i("Name of person is : ", person.getName()); } |
Create an event
1 2 |
EventBus bus=EventBus.getDefault(); bus.post(new PersonClass("Android Gig")); |
The library is optimized for the Android platform and is very lightweight. This means that you can use it in your projects without having to worry about the size of your app. To learn more about the EventBus library, visit the project on GitHub.
Ravi Rupareliya
Latest posts by Ravi Rupareliya (see all)
- Dialogflow Entities With Actions on Google - May 7, 2020
- Actions on Google Using Cloud Functions - February 3, 2020
- Create WhatsApp Stickers Android Application - April 19, 2019