31 October 2017

RxJava Publish Subject is pretty awesome


Hopefully you're all now using RxJava because it's pretty awesome. Now I'm not about to force on you another tutorial, there are plenty out there. I've been using RxJava for ages now and only just discovered a new thing. I love discovering new things, especially about something I've used for ages. So I discovered PublishSubject, this is basically an amazing alternative to creating callbacks all over the place.

Normally if I were to implement a callback from a fragment to an activity I'd do something like this:

public interface IFragmentListener{
    void onFragmentSuccess();
}

private IFragmentListener mFragmentListener;

Then of course my activity would implement that interface and receive callbacks when mFragmentListener is called.

However there's a better way to do things, and that's with publishSubject.

private PublishSubject<String> mSelectionObservable = PublishSubject.create();

mSelectionObservable.onNext("Hello");

public Observable<String> getSelectionObservable() {
    return mSelectionObservable;
}

PublishSubject allows you to declare an observable which you can subscribe to and send callbacks whenever you want. As you can see when I call mSelectionObservable.onNext().

Your activity can subscribe to the publishSubject like this

frag.getSelectionObservable()
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnNext(new Action1<String>() {
    @Override
    public void call(String s) {
        Log.d(TAG, "call: ");
        Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
    }
}).subscribe();

Hope that helps make your code more awesome!