CompositeDisposable.clear() does not stop Observable execution

Viewed 220

I use CompositeDisposable to observe a network call. The observable is inside a class that uses my activity context, so even after calling clear() in onDestroy(), the observable keeps running and its class holds a reference to my activity causing a memory leak. Is there any way to actually stop the process, instead of just stop observing it?

The class with the Observable

    public ProgressObservable(Context context) {
        super(context);
        createProgressObservable();
    }

    private void createProgressObservable() {
        progressObservable = authenticationObservable
                .flatMap((Function<Object, Observable<ProgressResponse>>)
                        Response -> Observable.fromCallable(() -> {
                            ...
                            ...
                            return pResponse;
                        })).cache();
    }

The creation of observable in my Activity

        Observable<ProgressResponse> prObservable = new ProgressObservable(context).getProgressObservable();
        disposable.add(prObservable
                .subscribe(progress -> mListener.onSilentRefreshComplete(),
                        error -> {
                        }));

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isFinishing()) {
            disposables.clear();
        }
    }
1 Answers

Props to u/bleeding182 from reddit, he pointed out the problem, which was using .cache(). From the documentation

  • You sacrifice the ability to dispose the origin when you use the {@code cache} Observer so be careful not to use this Observer on ObservableSources that emit an infinite or very large number of items that will use up memory.
Related