A simple event bus in Android using RxRelay | No BS Tutorials
Welcome to No BS Tutorials. Here you will get “To the Point” tutorials with no BS involved.
A detailed tutorial with thorough explanation will be found on my blog.
This tutorial will be in Kotlin
Goal :
Create a simple mechanism to communicate between different activities/fragments or basically anything as long as a listener is attached.
Getting Started :
- We will use Jake Wharton’s Rx Relay to accomplish this task.
Although Rx Relay is concept of Reactive programming , you don’t need any specific knowledge for this tutorial
- Add in build.gradle (app)
implementation 'com.jakewharton.rxrelay2:rxrelay:2.1.1'
- Create an empty kotlin file named anything (don’t make it class/interface or anything at all).
- Simply add
This is a very simple event where we will just send any kind of STRING between different components in our code
- Now let's send a simple “Hello” from Activity B— A
- Create a listener (subscriber) in Activity A.
- Apart from your code, Activity A should look like
- Now in Activity B just call
RxBus.accept("Hello")
Note : PublishRelay sends the event (from accept) to all available active listeners at that point — more info about various Relays here.
Conclusion:
VOILA !! That's all to it.
Here we have sent a String, in this very similar way we can send a MAP, PAIR, INT or any other data type.
You can send anything between anything even from A — B as long as a listener(subscriber) is attached (& not destroyed)
Once again if you wish to know in more detail about this entire tutorial visit my blog.
Thanks a lot for tuning in today, for more tutorials follow this publication or subscribe to my blog.