EventBus: Simplifying data sharing between components in Android

Read Time < 1 minute

In almost every android app there is a need to pass data between different components i.e Activities, Fragments, Services and threads. One case is very common and that is posting data to UI thread from background thread. Although android framework provide Handlers and AsyncTasks for this purpose but we all know they are not well tied with Activity/Fragment life cycle i.e device rotation and activity recreation can waste the background work.

EventBus  simplifies communication between different components. You can post Events [Any custom object] from any thread and you can receive those anywhere in the application. Receiver [fragment/Activity/Service etc] will just need to register with event Bus and the type of Events.

Lets Assume we want to receive List<User> from Background thread in our Fragment. Lets first define an Event for user list and exception.

public class EventUsers{
     final List<User> userList;
    final Exception exception;

    public EventUsers(List<User> users,Exception exception){
     this.userList=users;
     this.exception=exception;
}

We will post and receive the objects of the above class. To receive event of type EventUser we need add following in our fragment class.

@Override
public void onPause() {
    EventBus.getDefault().unregister(this);
   super.onPause();

}

@Override
public void onResume() {
   super.onResume();
   EventBus.getDefault().register(this);
}

public void onEventMainThraed(EventUsers event){
      //consume event 
}

We are basically registering/unregistering with event bus and telling it that we are interested in EventUser on UI thread. Now, no matter from which thread EventUser is posted, we will receive that event on UI thread.

To post this event from anywhere i.e from background thread we do

EventUsers eventUser=new EventUsers(new ArrayList<User>(),null);
EventBus.getDefault.post(eventUser);

EventBus library is very small in size [about 50Kb], To use it, add following dependency in your apps gradle.build

compile 'de.greenrobot:eventbus:2.4.0'

Happy coding 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *