Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How cancel task with retrofit and rxjava

Tags:

I have rest api.

@Get("/serveraction") public Observable<String> myRequest(@Query("Data") String data); 

I know, that okhttp has canceling functionality(by request object, by tag), but don't know how use it with retrofit and rxjava. What is the best way to realize canceling mechanism for network tasks with retrofit and rxjava?

like image 310
zella Avatar asked Jun 09 '15 08:06

zella


1 Answers

You can use the standard RxJava2 cancelling mechanism Disposable.

Observable<String> o = retrofit.getObservable(..); Disposable d = o.subscribe(...);  // later when not needed d.dispose(); 

Retrofit RxJava call adapter will redirect this to okHttp's cancel.

RxJava1: https://github.com/square/retrofit/blob/46dc939a0dfb470b3f52edc88552f6f7ebb49f42/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallArbiter.java#L50-L53

RxJava2: https://github.com/square/retrofit/blob/46dc939a0dfb470b3f52edc88552f6f7ebb49f42/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/CallEnqueueObservable.java#L92-L95

like image 83
Sergii Pechenizkyi Avatar answered Sep 16 '22 22:09

Sergii Pechenizkyi