vxhviet
7/7/2016 - 5:05 AM

Use RxJava as an EventBus

Use RxJava as an EventBus

Source: weddingPartyApp, Reddit, human-readable

Question: How to use RxJava as an EventBus

Answer:

Here are the interesting parts of the implementation:

// this is the middleman object
public class RxBus {

  private final Subject<Object, Object> bus = new SerializedSubject<>(PublishSubject.create());

  public void send(Object o) {
    bus.onNext(o);
  }

  public Observable<Object> toObserverable() {
    return bus;
  }
}

That’s it. You now have an event bus ready to use. Here’s how you post an event to the bus:

public void onTapButtonClicked() {
    rxBus.send(new TapEvent());
}

and here’s how you listen to those events from other fragments/services etc.

// note that it is important to subscribe to the exact same _rxBus instance that was used to post the events
rxBus.toObserverable()
    .subscribe(new Action1<Object>() {
      @Override
      public void call(Object event) {

        if(event instanceof TapEvent) {
          showTapText();

        }else if(event instanceof SomeOtherEvent) {
          doSomethingElse();
        }
      }
    });