Reputation: 4685
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?
Upvotes: 24
Views: 14160
Reputation: 5540
The chosen answer is for Rx Java 1 and is not valid for RxJava2. For the latter, you can use Disposable. Follow this:
CompositeDisposable compositeDisposable=new CompositeDisposable()
as a field in your Activity
or Fragment
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 the compositeDisposable
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 your Activity
or onDestroyView()
of your Fragment
) call
mCompositeDisposable.clear();
Multiple disposables may be added to the CompostieDisposable above this way.
Upvotes: 5
Reputation: 22232
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.
Upvotes: 38