Pub/Sub and Events

The publish subscribe pattern provides a great design to pass the information between widgets. We can send a message from one object to one or more other objects, without the sender or receivers having any reference or dependency to each other.

To make development easy, the Android SDK provides a built-in BroadcastReceiver. This class can pick up message broadcasts from other classes in the same app, or from the Android system and other Android apps, similar to the publish-subscribe design pattern.

Define events:

public static class MessageEvent { /* Additional fields if needed */ }

Prepare subscribers:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};

Register and unregister your subscriber.

@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}

@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}

Post events:

EventBus.getDefault().post(new MessageEvent());

Via Gradle:

implementation 'org.greenrobot:eventbus:3.2.0'

Via Maven:

<dependency>
<groupId>org.greenrobot</groupId>
<artifactId>eventbus</artifactId>
<version>3.2.0</version>
</dependency>

Benefits using EventBus

  • simplifies the communication between components
  • decouples event senders and receivers
  • performs well with UI artifacts (e.g. Activities, Fragments) and background threads
  • avoids complex and error-prone dependencies and life cycle issues
  • Convenient Annotation based API: Simply put the @Subscribe annotation to your subscriber methods. Because of a build time indexing of annotations, EventBus does not need to do annotation reflection during your app’s run time.
  • Android main thread delivery: When interacting with the UI, EventBus can deliver events in the main thread regardless how an event was posted.
  • Background thread delivery: If your subscriber does long running tasks, EventBus can also use background threads to avoid UI blocking.
  • Event & Subscriber inheritance: In EventBus, the object oriented paradigm apply to event and subscriber classes. Let’s say event class A is the superclass of B. Posted events of type B will also be posted to subscribers interested in A. Similarly the inheritance of subscriber classes are considered.
  • Jump start:You can get started immediately — without the need to configure anything — using a default EventBus instance available from anywhere in your code.
  • Configurable: To tweak EventBus to your requirements, you can adjust its behavior using the builder pattern.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store