EventBus Library For 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.

EventBus
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. EventBus bus = EventBus.getDefault();  
  2. 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.

Create an Event,
  1. EventBus bus=EventBus.getDefault();  
  2. bus.post("Pass Message here.");  
Pass Object in EventBus

Registering your component will be the same, the only change you need to do is in your onEvent() and pass your object while creating event.
  1. public class PersonClass  
  2. {  
  3.     String name;  
  4.     public PersonClass(String message)  
  5.     {  
  6.         this.name = name;  
  7.     }  
  8.     public String getName()  
  9.     {  
  10.         return name;  
  11.     }  
  12.     public void setName(String name)  
  13.     {  
  14.         this.name = name;  
  15.     }  
  16. }  
  17. change parameter in onEvent()  
  18. @Subscribe  
  19. public void onEvent(PersonClass person)  
  20. {  
  21.     Log.i("Name of person is : ", person.getName());  
  22. }  
Create an event,
  1. EventBus bus=EventBus.getDefault();  
  2. bus.post(new PersonClass("Ravi Rupareliya"));  
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.