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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Yubaraj poudel
Yubaraj poudel

Written by Yubaraj poudel

Senior Software engineer | Blogger

No responses yet

Write a response