rxjava and rxandroid are libraries for managing the threading and background tasks in Android applications. They can also be used to implement the Event Bus mechanism. It is so good that even the dedicated Event Bus library otto is deprecated in favor of rxjava and rxandroid. This post will go through the steps of implementing event bus using rxjava 2 in Android.
1. Import rxjava and rxandroid in your gradle file.
2. Create a simple java class called RxEventBus.java
public class RxEventBus {
public RxEventBus() {
}
private PublishSubject
3. Create java class called Events.java, this will be used as message object to put and get information from the event bus.
public class Events {
private Events(){}
public static class Message {
private String message;
public Message(String message) {
this.message = DateFormat.format("MM/dd/yy h:mm:ss aa", System.currentTimeMillis()) + ": " + message;
}
public String getMessage() {
return message;
}
}
}
4. With the above, we already set up an Event Bus for us to use. From here on, let’s go through how to use it. Go ahead and create a MyApp.java that extends the Application class.
public class MyApp extends Application {
private RxEventBus bus;
@Override
public void onCreate() {
bus = new RxEventBus();
Log.d("before", "" + System.currentTimeMillis());
new Thread() {
@Override
public void run() {
SystemClock.sleep(3000);
bus.send(new Events.Message("Hey I just took a nap, how are you!"));
}
}.start();
Log.d("after ", "" + System.currentTimeMillis());
}
public RxEventBus bus() {
return bus;
}
}
5. Receiving messages in the MainActivity.java, the message is received after this line of code bus.send(new Events.Message("Hey I just took a nap, how are you!")); in the onCreate of the MyApp