EventBus is an open-source Android library that simplifies communication between Activities, Fragments, Threads, and Services, with less code and better quality. When we develop an Android application, we need to manage a lot of intercommunication between Android components, which sometimes becomes very difficult to manage. The EventBus library makes this task easy.

Why EventBus?

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

The last two steps are to register and unregister the EventBus that wants to listen to the event. The best way is to register it in the onStart method and unregister it in the onStop method of the activity.

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

Implementation of EventBus

Add the dependencies in the gradle file.

compile 'de.greenrobot:eventbus:2.4.0'

Add the intent service class, which will start at the time of application launch.

If any other component of your application wants to listen to the event, we only need to register for the EventBus as mentioned in the above method onStart and override the method onEvent.

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