What is EventBus Library and How Does it Work?

In this blog, we are going to discuss about the Eventbus library.

What is EventBus:

EventBus Is open Source android library that simplifies communication between Activities, Fragments, Threads, Services, with Less code, better quality.When we develop an android application we need to manage a lot of intercommunication between android components which some time’s become very difficult to manage. Eventbus library makes this task easy to implement.

Why EventBus?

The main reason why we should use EventBus is loose coupling. Sometimes you want to process specific events that are interested for multiple parts of your application like presentation layer business layer and data layer so EventBus provides a easy solution
for this.

Some features of EventBus library:

1-Simple yet powerful:
2- Battle tested:
3-High Performance
4-Convenient Annotation based API
5-Event & Subscriber inheritance

you need to have four thing for implement EventBus:

1– A EventBus Object .

2- A Event normal pojo class.

3- The sender which will send the event:

4- The subscriber is someone who will listen to our event.

The last two step are Register and unregister the Eventbus who want to listen to the event. The best way is register in onStart method and unRegister in the onStop method of activity.

Example of EventBus:

Let’s take a simple example, In our project, if we want to Sync our data to the server at the time of applicaiton launch, for this, simply start an intent service from the launcher activity of your application and through intent service sync the data to the server. After that notify the screen(Through EventBus library) which is currently visible to user about syncing.

Implementation of EventBus:

Add the dependencies in the gradle file.

Intent service class which will start at the time of application launch.

The Maine Activity.

If any other component of you applicaiton want to listen to the event then only we need to register for the EventBus as mentioned in above method onStart and override the method onEvent.

Conclusion:

Eventbus library is just like a radio frequency, if you wish to listen to any song, you simply need to set the frequency to that station. Likewise, event bus library posts events, if any component wants to listen that event then we need to register that component for the EventBus object and we will get that event in onEvent Method.

Leave a Reply