Retrofit 2 + RxJava cancel/unsubscribe

Sermilion picture Sermilion · Jun 15, 2017 · Viewed 15.3k times · Source

I am performing a network request where I send files and a message. I would like to have an option to cancel current request. I have found two similar questions and both suggests that observable.subscribe(Observer) returns Subscription object which has method unsubscribe().

Here is the first one

And the second one

In my case, I use observable.subscribe(Observer) which is void. Here is my code:

Observable<MessengerRaw> observable = mModel.sendMessage(message, companion, description, multiParts);
        observable.subscribe(new Observer<MessengerRaw>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(MessengerRaw value) {
                if (getView() != null) {
                    ((MessengerActivity) getView()).resetMessegeView();
                    ((MessengerActivity) getView()).updateMessageList();
                }
            }

            @Override
            public void onError(Throwable e) {
                getData().remove(0);
                if (getView() != null) {
                    ((MessengerActivity) getView()).updateMessageList();
                }
            }

            @Override
            public void onComplete() {
                hideProgress();
            }
        });

So how do I unsubscribe/cancel my request? Thank you.

Answer

Arnav Rao picture Arnav Rao · Jun 16, 2017

In RxJava2, you can get Disposable object in onSubscribe callback method of oserver, which you can use to dispose subscription.