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 .

EventBus myEventBus = EventBus.getDefault();

2- A Event normal pojo class.

public class DataSyncEvent {
    private final String syncStatusMessage;

    public DataSyncEvent(String syncStatusMessage) {
        this.syncStatusMessage = syncStatusMessage;
    }

    public String getSyncStatusMessage() {
        return syncStatusMessage;
    }
}

3- The sender which will send the event:

EventBus.getDefault().post(new DataSyncEvent("Sync SuccessFully”);

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

@Subscribe
public void onEvent(DataSyncEvent syncStatusMessage)
{
    Toast.makeText(this, syncStatusMessage.getSyncStatusMessage(), Toast.LENGTH_SHORT).show();
}

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.

@Override
protected void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}

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.

compile 'de.greenrobot:eventbus:2.4.0'

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

    public class SyncDataService extends IntentService
    {
        public SyncDataService()
        {
            super("SyncDataService");
        }

        @Override
        protected void onHandleIntent(Intent intent)
        {
            //first check if internet is availabe or not.
            if(DeviceManager.isInternetAvailableOnDevice())
            {
//            try
//            {
//              //write the code to sync the data to Server
                //post the event after sync complete 
                EventBus.getDefault().post(new DataSyncEvent("Data Sync SuccessFully"));
//            }
//            catch (RTITBException exception)
//            {
//                LogManager.getInstance().addLog(exception.getExceptionCode(),exception.getMessage(),exception);
//            }
            }
        }
    }

The Maine Activity.

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //Register the EventBus
    @Override
    protected void onStart()
    {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    //UnRegister the EventBus
    @Override
    protected void onStop()
    {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    //The Method which will call every time when data sync to server
    @Subscribe
    public void onEvent(DataSyncEvent syncStatusMessage)
    {
        //you can do whatever you want releted with UI
        Toast.makeText(this, syncStatusMessage.getMessage(), Toast.LENGTH_SHORT).show(); 
    }
}

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