Abhishek Borikar
Abhishek Borikar

Reputation: 434

RxJava call disposable dispose()

I am using rxjava with retrofit. In the following code the subscribeOn() and observeOn() keeps running. The App terminates and launched by itself continuously.

disposable = api.getUsers("135")
                .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                users -> showResult(users)
            })

If I dispose right after the above it won't fetch complete data. So my question is when to dispose dispoable or how to know when subscribeOn() and observeOn() has completed it's task.

Upvotes: 3

Views: 14048

Answers (1)

Sachin Rajput
Sachin Rajput

Reputation: 4344

either you can dispose in onDestroy() of your Activity.

or you can use DisposableSingleObserver for good , like this :

Disposable disposable = yourApi.subscribeWith(new DisposableSingleObserver<List<String>>() {

        @Override
        public void onSuccess(List<String> values) {
            // work with the resulting values
        }

        @Override
        public void onError(Throwable e) {
            // handle the error case
        }
    });

and then after you use the result (in this example case when you no longer need the values(api response) you can call dispose

    disposable.dispose();

best place to dispose an observer will be in onDestory() , this will be the place where you no longer will be needing api result:

protected void onDestroy(){
    super.onDestroy();
    disposable.dispose();
}

Upvotes: 3

Related Questions