1

I'm using RxJava2 and Retrofit. In my fragment, I make a request to upload a local file:

Disposable disposable = mApi.requestUpload(file)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(response -> {
            toast("success");
        }, throwable -> {
            toast("failed");
        });
mCompositeDisposable.add(disposable);

Then, clear all disposables in onDestroyView()

@Override
public void onDestroyView() {
    mCompositeDisposable.clear();
    super.onDestroyView();
}

But I use Charles to view all requests and find that the request is still executing after I finish the fragment. The file is still uploaded successfully after a time.

How can I cancel the call when fragment closed?

Ebn Zhang
  • 241
  • 2
  • 9

3 Answers3

1

use disposable.dipose() for canceling your call.

aolphn
  • 2,950
  • 2
  • 21
  • 30
  • 2
    `mCompositeDisposable.clear();` should dispose and clear all `Disposable`s added. I'm pretty sure that `disposable.dispose()` is called. – Ebn Zhang Nov 11 '18 at 07:08
0
  1. Define Disposable

    private io.reactivex.disposables.Disposable mDisposable;

  2. assign to your service

    mService.getResults(query)
                .observeOn(AndroidSchedulers.from(Looper.getMainLooper(), true))
                .subscribeOn(Schedulers.io())
                .subscribe(new SingleObserver<Response<Model>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        /* required */
                        mDisposable = d;
                    }
    
                    @Override
                    public void onSuccess(Response<Model> response) {
                        dismissProgress();
                    }
    
                    @Override
                    public void onError(Throwable e) {
    
                    }
                });
    
  3. call below line to dismiss/terminate ongoing API call

     if (mDisposable != null)
        mDisposable.dispose(); 
    

There you go.

UPDATE

in your case, it should be

@Override
public void onDestroyView() {
if (mCompositeDisposable!= null) // in case if you required-> if (mCompositeDisposable!= null && !mCompositeDisposable.isDisposed())
      mCompositeDisposable.dispose(); 
super.onDestroyView();
}
Aks4125
  • 4,522
  • 4
  • 32
  • 48
  • Thanks for your answer! I already use code like your answer, but still not work. Dispose all Disposable only unsubscribe the result of current call, but not really stop uploading file. And I found that cancel a Http call is not reliable, so maybe my question is not about RxJava...... – Ebn Zhang Nov 24 '18 at 18:57
  • @EbnZhang in this case https://futurestud.io/tutorials/retrofit-2-cancel-requests. – Aks4125 Nov 26 '18 at 08:24
0

Add RxJava to CompositeDisposable Then in onStop() use disposableRxJava.dispose()

Shaon
  • 2,496
  • 26
  • 27