0

I tried calling it on the onComplete() block but compositeDisposables.clear() with retrofit network calls causes the calls to be cancelled midway.

                               observable.......
                               .subscribe(
                                {
                                    utilModule.logI("net repo response")
                                    //cleanDisposables()//this causes HttpOk cancelled error
                                },
                                {
                                    utilModule.logI("no repo response" + it.message)
                                    //cleanDisposables()
                                }
                        ))
    }

    private fun cleanDisposables() {
        //clean old network observables, dispose will prevent further observing
        utilModule.logI("disposing observables")
        if (!compositeDisposables.isDisposed) {
            compositeDisposables.clear()
        }
    }
ir2pid
  • 5,604
  • 12
  • 63
  • 107

2 Answers2

4

Typically your disposables would be tied to your activity or fragments lifecycle and clear in onDestroy.

This could be an example using MVP design pattern...

presenter.kt
fun dispose() {
    compositeDisposable.clear()
}


activity.kt
override fun onDestroy() {
    super.onDestroy()
    presenter.dispose()
}
tgrable
  • 1,013
  • 1
  • 7
  • 15
  • My disposables are in the repository class which is referenced in the presenter, that's two layers away from the activity/fragment. This seems to be getting messy. – ir2pid Jun 12 '18 at 19:47
  • 1
    Have you tried calling cleanDisposables() in .doOnComplete{ }? – tgrable Jun 12 '18 at 20:32
  • i m little confused , so to clear a compositedisposable in presenter ( mvp ) , we can Dooncomplete() and inside it , we compositeDisposable.clear(), is that correct – Taki Jul 20 '20 at 01:12
2

Here is how I do it in MVVM. I have LifeCycle-ed Activity that subscibes to my ViewModel. Then In ViewModel class I have instance of CompositeDisposable. I do clear it in the ViewModel onCleared method.

here is a stub

public class MyViewModel extends AndroidViewModel {
    private MyRepo mRepo;
    private CompositeDisposable mDisposables = new CompositeDisposable();


    public MyViewModel(@NonNull Application application) {
        super(application);

        mRepo = MysRepo.getInstance(...);
    }

    public void loadData()
    {
        Disposable d = mRepo.getMyPeculiarData()
                ...
                .subscribe(...);

        mDisposables.add(d);
    }


    @Override
    protected void onCleared() {
        super.onCleared();
        mDisposables.clear();
    }

}
Stefano Mtangoo
  • 6,017
  • 6
  • 47
  • 93