Communication between the components using the EventBus in android

Yubaraj poudel
1 min readMar 22, 2021

EventBus is widely used light weight and easy to integrate third party support library for communication between the different components in the android. It provides annotation based API which makes the code readable and easy to use.

To add the EventBus in project inside project -> app -> build.gradle add the following dependencies and sync

implementation 'org.greenrobot:eventbus:<latest version>'

Next Lets make the POJO class to make things easier

public class ProductEvent {
public String ProductName;

public ProductEvent(String productItem) {
this.productItem = productItem;
}
}

Add the subscribe method to tell the EventBus to trigger. This the function that will get called by Eventbus to perform a task.

@Subscribe
public void onProductItemAdd(ProductEvent productEvent){
// your logic here
}

Register the event bus in the activity

@Override
protected void onStart() {
super.onStart();
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}

Now finally to create the event to post the data, this will invoke the method anotonated by subscribe.

public void addProductToCart(View view) {
EventBus.getDefault().post(new ProductEvent("new Cart Item"));
}

Thats all, This simplifies the process of broadcast receiver with easy steps.

--

--