Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 998
Abhishek Borikar Avatar asked May 02 '26 18:05

Abhishek Borikar


1 Answers

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();
}
like image 142
Sachin Avatar answered May 05 '26 08:05

Sachin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!