rx-javarx-java2rx-android

How to explicitly unSubscribe from observable after the onComplete


In the following code, how and where to put unSubscribe to make un-subscription of the Observable explicitly exactly after finishing the onComplete?.

getObservable()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    .subscribe(new Subscriber<Boolean>() {
        @Override
        public void onCompleted() {
            doSomething();
        }

        @Override
        public void onError(Throwable e) {
            thereIsError();
        }

        @Override
        public void onNext(Boolean status) {
            updateView();
        }
    });

Solution

  • You can save Disposable returned by subscribe method and use it inside onCompleted callback

    Disposable d = 
    getObservable()
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
        .subscribe(new Subscriber<Boolean>() {
            @Override
            public void onCompleted() {
                doSomething();
                d.dispose();
            }
    
            @Override
            public void onError(Throwable e) {
                thereIsError();
            }
    
            @Override
            public void onNext(Boolean status) {
                updateView();
            }
        });