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.
In RxJava2, you can get Disposable object in onSubscribe callback method of oserver, which you can use to dispose subscription.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With