Let's explore Event Bus in Android

No alt text provided for this image

Event Bus: Communicating with an Event Bus

 

Overview:

It is difficult to change one part of the system without impacting another area. Event buses are especially helpful include notifying activities or fragments when tasks are completed, such as when a AsyncTask or a Background Service finishes


What is "Event Bus"?

EventBus is an open-source library for Android and Java using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development.


Why I need to use "Event Bus"?

1. It simplifies the communication between components

2. It decouples event senders and receiver

3. It avoids complex and error-prone dependencies and life cycle issues

4. It is fast; specifically optimized for high performance

5. It is tiny (~60k jar)


How to Setting up an Event Bus in my project?


Step 1: Add this Gradle dependency to your app/build.gradle file:

implementation 'org.greenrobot:eventbus:3.2.0'


Via Maven:

<dependency>

<groupId>org.greenrobot</groupId>

<artifactId>eventbus</artifactId>

<version>3.2.0</version>

</dependency>


R8, ProGuard

If your project uses R8 or ProGuard add the following rules:


-keepattributes *Annotation*

-keepclassmembers class * {

   @org.greenrobot.eventbus.Subscribe <methods>;

}

-keep enum org.greenrobot.eventbus.ThreadMode { *; }


# And if you use AsyncExecutor:

-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {

<init>(java.lang.Throwable);

}


Step 2: write down below line in your onResume() to register Event Bus


GlobalBus.getBus().unregister(this);


Step 3: Register your class for event operations

public class RefreshView{

   public boolean refresh;


   public RefreshView(boolean refresh) {

       this.refresh = refresh;


   }


   public boolean isRefresh() {

       return refresh;

   }


}


Step 4: Subscribe a event

@Subscribe

   public void getMessage(RefreshView refreshViewObj) {

   if(refreshViewObj.isRefresh()){

   //refresh your view

   }


Step 5: Don't forget to unregister this bus on onDestroy()

GlobalBus.getBus().unregister(this);



Here you go! Happy Coding!

要查看或添加评论,请登录

Janakkumar T.的更多文章

社区洞察

其他会员也浏览了