How cancel task with retrofit and rxjava
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
The chosen answer is for Rx Java 1 and is not valid for RxJava2. For the latter, you can use Disposable. Follow this:
- Define
CompositeDisposable compositeDisposable=new CompositeDisposable()
as a field in yourActivity
orFragment
in class. Define the api using Retrofit 2 as something like this:
public Observable<YourPojo> callApiWithRetrofit() { return getService(YourApiService.class).callApi(); }
Define
Disposable
and add it to thecompositeDisposable
instance:Disposable disposable = callApiWithRetrofit().subscribeOn(Schedulers.io()).observeOn( AndroidSchedulers.mainThread()).subscribeWith( new DisposableObserver<List<YourPojo>>() { @Override protected void onStart() { super.onStart(); } @Override public void onNext(@NonNull List<AlertAssetDTO> listResponse) { } @Override public void onError(@NonNull Throwable e) { } @Override public void onComplete() { } }); mCompositeDisposable.add(disposable);
Wherever you want the connection to be cancelled (e.g.
onDestroy()
method of yourActivity
oronDestroyView()
of yourFragment
) call mCompositeDisposable.clear();
Multiple disposables may be added to the CompostieDisposable above this way.