Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2 + RxJava cancel/unsubscribe

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.

like image 333
Sermilion Avatar asked Jun 15 '17 18:06

Sermilion


2 Answers

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

like image 53
Arnav Rao Avatar answered Sep 22 '22 21:09

Arnav Rao


In RXJava You must use subscriptions for unsubscribe

private Subscription mSubscription;

/.../

Observable<MessengerRaw> observable = mModel.sendMessage(message, companion, description, multiParts);
Subscription subscription = observable.subscribe(new Observer<MessengerRaw>() {/.../});

When you want to unsubscribe you can call

if(!subscription.isUnsubscribed()){
    subscription.unsubscribe();
}

In RXJava 2 observable.subscribe(new Observer<MessengerRaw>() {/.../}); returns Disposable object, you can call dispose();

like image 31
Gevork Safaryan Avatar answered Sep 22 '22 21:09

Gevork Safaryan