MaChee Neraid
MaChee Neraid

Reputation: 1043

android, how to cancel current request in retrofit2/rxjava-android

I am new in retrofit/rxjava-android

Someone told me that, it is best practice if I will cancel the request if the call is not yet finished and the user leaves the activity page.

I am having problem where/how to cancel it.

Here's my code, it is working properly.

Observable<List<MyObject>> call;
public void getStaticMessages() {
    call = restInterface.loginURL();
    call.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<MyObject>>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            Log.d("LOGGER", "error");
        }

        @Override
        public void onNext(List<MyObject> myObjects) {
            Log.d("LOGGER", "succcess");
        }
    });

}

Upvotes: 1

Views: 1536

Answers (1)

Valerii
Valerii

Reputation: 405

One of the best practice is to create subscription/disposable when onStart() method of activity/fragment is called and unsubscribe /dispose when onStop called.

You can create one disposable Disposable disposable = call.subscribeOn and dispose it via disposable.dispose() or use CompositeDisposable.

I used the same approach with CompositeDisposable in one of my previous pet projects - link

Upvotes: 1

Related Questions