Michael Vescovo Michael Vescovo - 3 years ago 234
Android Question

DisposableCompletableObserver leaking Activity even though I'm clearing CompositeDisposable

I'm new to RxJava and LeakCanary so this might be something simple (hopefully).

Essentially I have an Activity which includes a

CompositeDisposable
. I get the instance of my Singleton repository and use it to get a
Completable
that is added to the
CompositeDisposable
.

In onPause I clear the
CompositeDisposable
which I'm led to believe will avoid any memory leaks of the calling object (in this case an Activity).

Unfortunately after installing LeakCanary it reports that this Activity is leaked in the repository via the
Completable
.

What am I doing wrong? When Googling it, I don't see anything extra that people are doing.




Note:

Normally I get an observable from my repository via an
AndroidViewModel
, however in this case I'm using my Settings Activity which has a requirement to make one call to the repository. It doesn't require a ViewModel.

Anyway, because of this LeakCanary was able to notice the Activity was leaked. If I'm not mistaken by default it wouldn't be able to do this on my ViewModels unless I told it to.

So perhaps everything else is being leaked as well but I'm just not aware of it. Ok I just watched one of my AndroidViewModel's and sure enough it's being leaked also (according to LeakCanary). It seems either I'm doing something wrong or LeakCanary is showing a false positive.

Any help appreciated.
Thanks.




Code as requested (updated):

private CompositeDisposable mSubscriptions;

@Override
public void onCreate(Bundle savedInstanceState) {
...
mSubscriptions = new CompositeDisposable();
...
}

@Override
protected void onPause() {
super.onPause();
mSubscriptions.clear();
}

public void someMethodForButtonClick(View view) {
IwcRepository iwcRepository =
Injection.provideIwcRepository(getApplication());
mSubscriptions.add(iwcRepository.getSomeCompletable()
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableCompletableObserver() {
@Override
public void onComplete() {

}

@Override
public void onError(@NonNull Throwable e) {

}
}));
}


LeakCanary Screenshot:

enter image description here

Answer Source

Ok so as mentioned in the comments I resolved this error by removing the CompositeDisposable from the repository. New to RxJava I didn't know how to use it properly. I had subscriptions inside subscriptions rather than chaining and returning one observable, and subscribing once at the end of the chain. I.e. my repository didn't actually need to subscribe to anything, it just needed to tack on some logic or do some "andThen's".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download