Implementing EventBus With RxJava — RxBus

Ff314 1yc7epvj3nb8mk_iezl8xpq

RxBus implementation with RxJava2

When we implement the EventBus pattern with RxJava, we call it as RxBus.

Note: This is just an example.

So, let’s see how we can create RxBus using RxJava 2.

First of all, We must have knowledge of the subject in RxJava. For that, you can refer to my previous article on RxJava Subject.

After having knowledge of RxJava Subject, we can create RxBus like below.

public class RxBus {

    public RxBus() {

    private PublishSubject<Object> bus = PublishSubject.create();

    public void send(Object o) {

    public Observable<Object> toObservable() {
        return bus;


Now, we will create the Singleton(single instance) of RxBus in our application class or at any other place as below:

public class MyApplication extends Application {

    private RxBus bus;

    public void onCreate() {
        bus = new RxBus();

    public RxBus bus() {
        return bus;


So, now we have access to RxBus from anywhere.

We can subscribe for an event in any class like below:

((MyApplication) getApplication())
        .subscribe(new Consumer<Object>() {
            public void accept(Object object) throws Exception {
                if (object instanceof EventTypeOne) {
                    Logger.d("Event Type One Received");
                } else if (object instanceof EventTypeTwo) {
                    Logger.d("Event Type Two Received");

We can send an event from any other class or from the same class like below:

((MyApplication) getApplication())
        .send(new EventTypeOne());

This way, we have the EventBus pattern with RxJava, RxBus.

But if there is some error, it will terminate, so to avoid that check RxRelay.

RxRelay: A Subject except without the ability to call onComplete or onError.

Check out the complete code in this project.

By the way, we at Mindorks, created the EventBus using the RxJava(RxJava2) and open-sourced it. Check here.

Check the project to learn how to create a library with proper coding, how to create a pub/sub library, and documentation. I love New York City, so named the library as NYBus(New York Bus). I am sure you will love it and learn a lot from the NYBus.

Happy Learning :)

You can connect with me here.

Also, Let’s become friends on Twitter, Linkedin, Github, Quora, and Facebook.