Building an EventBus with RxJava2 (using Kotlin)

2 min read

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    // ...

    implementation 'io.reactivex.rxjava2:rxjava:2.0.7'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'

    // ...
}

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.

import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject

enum class MessageEventBus {

    INSTANCE;

    private val bus = PublishSubject.create<String>() // the actual publisher handling all of the events

    fun send(message: String) {
        bus.onNext(message) // the message being sent to all subscribers
    }

    fun toObserverable(): Observable<String> {
        return bus // return the publisher itself as an observable to subscribe to
    }

}

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:

MessageEventBus.INSTANCE.send("Hello World!")

Subscriber usage:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        MessageEventBus.INSTANCE.toObserverable().subscribe({
            println(it) // this prints the actual message
        })
    }
}

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.