Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel request with retofit2 and RxAndroid

I am using Retrofit 2.0 and Rx-android to load my APIs. I follow the section RxJava Integration with CallAdapter at this site and it work fine. But, I don't know how to cancel a loading request with the observable object. Please help to give me an idea.

like image 542
Nguyen Minh Binh Avatar asked Dec 10 '15 10:12

Nguyen Minh Binh


People also ask

How do I cancel a Rxjava request?

If you want to start loading - send True else False. 'switchMap' operator is designed to dispose previous observable. So it you send True it will start loading. If you send False it will dispose (cancel) previous observable.


1 Answers

The only way to cancel RxJava Observable execution - unsubscribe from it. RxJavaCallAdapter will delegate cancel to okhttp client.

So, you simple do smth like this:

Subscription subscription = getObservable().subscribe();

//When you want to stop execution
subscription.unsubsribe();

You can check out the code here. Concretely these lines if code

final Call<T> call = originalCall.clone();

// Attempt to cancel the call if it is still in-flight on unsubscription.
subscriber.add(Subscriptions.create(new Action0() {
  @Override public void call() {
    call.cancel();
  }
}));
like image 191
Vasilov Artur Avatar answered Oct 02 '22 15:10

Vasilov Artur