Building an EventBus with RxJava2 (using Kotlin)

There are many Android libraries out there which allow us to create an event bus without much work. But many times we do not want the overhead of everything else that comes along with third-party libraries. Lets take a moment to discuss how we can very easily create an event bus using RxJava2.

First things first. The dependencies. In your application level build.gradle file add the following. You can replace implementation with compile if you are not using the latest gradle plugin (4.0) or higher at the time of this post

For more information visit https://github.com/ReactiveX/RxJava

In order to create an event bus using RxJava 2 we need to use one of its subject classes such as the PublishSubject.

First of all, the bus will be a singleton, in this case an enum singleton. We will not get into the why I’ve chosen an enum singleton in Android, or what the best solution is, but lets look past this.

This is pretty straight forward. The send method sends the message to all the subscribers, and the subscribers listen to the messages being sent using the toObservable method and subscribing to it.

Sender usage:

Subscriber usage:

This can be used in many ways not just with strings, but also with custom objects to notify listeners of UI changes, new downloads available, etc.

That’s all for now! Hope you enjoyed.