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.

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

Register your component to receive events

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

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.

change parameter in onEvent()

Create an event

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.

Runtime Permission in Pre-Marshmallow
Tip : Underlining text in TextView

  • Arth Tilva

    Nice post.
    Is it possible to overload onEvent() ?

    • admin

      yes it is, as you can check it in above code also, we have onEvent() with String as well as PersonClass.

    • Ravi

      Yes it is, as you can see it in above code we have onEvent() with String as well as PersonClass