Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

What Is the EventBus Library and How Does It Work?

DZone's Guide to

What Is the EventBus Library and How Does It Work?

Learn about the EventBus library for Android and how it makes it easier to manage communication between components in your application.

· Mobile Zone ·
Free Resource

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 solution
for this.

Features of the EventBus Library

  1. Simple, yet powerful.

  2. Battle-tested.

  3. High performance.

  4. Convenient annotation-based API.

  5. Event and subscriber inheritance.

You need to have four things to implement EventBus:


1. An EventBus object.

EventBus myEventBus = EventBus.getDefault();

2. An 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, 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 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.

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

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.

    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 main 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 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.

Topics:
eventbus ,event listeners ,mobile ,mobile app development ,tutorial ,android

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}