Photo by Herson Rodriguez on Unsplash

Super simple event bus with RxJava and Kotlin

Dai
AndroidPub
Published in
2 min readMar 11, 2017

--

I wanted to implement a simple event bus with RxJava and Kotlin that did not require any if statements, switch statements, when statements, reflection or any other nasty-ness when deciding which consumers should receive the events. I am assuming any readers have used RxJava before but the idea is simple.

All we do here is create a Kotlin object (RxBus), which will ensure the RxBus is a singleton. We then instantiate a private PublishSubject<Any> on the RxBus and expose a publish method on the RxBus to send onNext(Any) events into the publisher.

The bit that makes the bus flexible for new events going forward is the listen function. Firstly we only want the listen function to return the Observable interface to make sure an event consumer can only observe events.

Now, when we call the listen(Class<T>) function on a consumer, we pass in the Class type for the event data we want to receive when subscribing. We then create an Observable from the publisher that filters and only emits events of this type using the ofType() method.

As you can see from the snippet above we can now listen out for any type of event just by using the class type. This also allows us to easily add or send new events without having to define separate event type classes or add any if/switch statements.

Omitted from this example, but I am assuming you have used RxJava and know to dispose of you subscriptions when finished.

That’s it. Thanks for reading.

--

--

Dai
AndroidPub

Engineering Manager (Client Platforms) @Plex