Implementing EventBus With RxJava — RxBus

RxBus implementation with RxJava2

When we implement 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 the knowledge of subject in RxJava. For that you can refer 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) {
        bus.onNext(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;

    @Override
    public void onCreate() {
        super.onCreate();
        bus = new RxBus();
    }

    public RxBus bus() {
        return bus;
    }

}

So, now we have the access of RxBus from anywhere.

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

((MyApplication) getApplication())
        .bus()
        .toObservable()
        .subscribe(new Consumer<Object>() {
            @Override
            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())
        .bus()
        .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 :)

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