19

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.

Sermilion
  • 1,920
  • 3
  • 35
  • 54

2 Answers2

20

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

Arnav Rao
  • 6,692
  • 2
  • 34
  • 31
  • I will mark this answer as accepted because it directly points to the solution. The previously accepted answer was not edited properly. Cheers. – Sermilion Jun 16 '17 at 13:39
5

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();

Gevork Safaryan
  • 237
  • 1
  • 7