Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        }
    });
like image 950
Adham Enaya Avatar asked Dec 24 '17 07:12

Adham Enaya


1 Answers

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();
        }
    });
like image 135
Tuby Avatar answered Oct 14 '22 23:10

Tuby