Skip to content

Instantly share code, notes, and snippets.

@bluemix
Last active December 22, 2016 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluemix/cf3b8206cb2e2bde8acf8f1f89ad7fd4 to your computer and use it in GitHub Desktop.
Save bluemix/cf3b8206cb2e2bde8acf8f1f89ad7fd4 to your computer and use it in GitHub Desktop.
RxAndroid and Retrolambda as an EventBus

RxBus.Java

public class RxBus {
    private static RxBus myInstance = new RxBus();
    private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
    ...
    
    public static RxBus singleton() {
        if (myInstance == null) {
            throw new NullPointerException("RxBux is not initialized.");
        }
        return myInstance;
    }

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

    public Observable<Object> toObservable() {
        return _bus;
    }
}

Sending

     RxBus.singleton().send("hello");

Receiving & Unsubscription

    private Subscription subscriber;
   
   ...
     subscriber = 
        RxBus.singleton().toObservable()
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(s -> {
                  ...
          });

// finishing or exiting
subscriber.unsubscribe();   
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment