Decoupled android app communication with EventBus
--
While creating an app which had a lot of in app communication in use, I used broadcast receivers with bundles and parcelables. It quickly grew into a lot of code which was tightly coupled and hard to keep track of. Not to mention the time spent removing error cases due to activity and fragment lifecycle events.
So I decided to find a better way out for this, I came across a post about loose coupled in app communication using EventBus and I decided to give it try.
EventBus is an open-source library for Android using the publisher/subscriber pattern for loose coupling.
The event bus :
• simplifies the communication between app components.
• decouples event senders and receivers.
• helps avoid complex and error-prone dependencies and life cycle issues in activities & fragments.
• can be used with services. Awesome!
• makes your code super simple.
• is a tiny library which is way faster.
• has advanced features like delivery threads, subscriber priorities, etc.
Wait, there is more:
• annotation based api.
• Main and background thread delivery.
• event and subscriber inheritance.
• configurable to your requirements.
• sticky events.
And after you are all impressed and ready to move to the first tutorial you can put your hands on, hold on it just takes 3 steps.
1. Define events:
public class LocationEvent { Location location; public LocationEvent(Location location) {
this.location = location;
} public Location getLocation() {
return location;
}
}
2. Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:
@Subscribe
public void onLocationEvent(LocationEvent event) {
/* Do what you need to */
};