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.
Asked
Active
Viewed 5,774 times
7

Nguyen Minh Binh
- 23,891
- 30
- 115
- 165
1 Answers
17
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();
}
}));

Vasilov Artur
- 1,467
- 1
- 14
- 18
-
I just test the 'unsubsribe()' and see that it works. The subscriber won't be called any more. But why okhttp continue prints the log many time. How can I check that the okhttp will be cancel? – Nguyen Minh Binh Dec 10 '15 at 16:02
-
1I've checked it too, It works, simpli prints GET and END GET. But of course not any request could be stopped. May be you've got in this case. But it still the only way to cancel request and it is absolutely the same to Retrofit Call cancel. You can check it by putting breakpoint to call.cancel(); e.g. – Vasilov Artur Dec 10 '15 at 16:25
-
Thank you, Vasilov. Since it's only way, I will use it until I find a better solution – Nguyen Minh Binh Dec 10 '15 at 17:12
-
@VasilovArtur The link to the source code is broken. This is the latest link https://github.com/square/retrofit/blob/master/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java And it doesn't contain that code snippet you provided. – Etienne Lawlor Feb 15 '17 at 01:54
-
1@toobsco42 in fact that changes nothing. Call is still cancelled when you unsubscribe, now it's here https://github.com/square/retrofit/blob/master/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallArbiter.java#L47 – Vasilov Artur Feb 15 '17 at 05:11
-
How can you check if a call was cancelled inside of an Observer's callback methods? – Etienne Lawlor Feb 15 '17 at 06:04