Magren

Magren

Idealist & Garbage maker 🛸
twitter
jike

CompositeDisposable in RxJava

I found that I missed some knowledge points when studying RxJava before, so I will supplement with another knowledge point here. That is the CompositeDisposable class.

When using RxJava with Retrofit, when sending a request and obtaining data, we often need to refresh the page to display the data in the view. However, if the network is slow and we quickly close the current activity while the request is being sent, RxJava will throw a NullPointerException when trying to refresh the interface after receiving the returned data. This means that if our UI layer is destroyed during the request process and we do not unsubscribe in time, it will cause memory leaks. This is where our CompositeDisposable comes in.

Usage#

The usage is roughly three steps:

  • Instantiate our CompositeDisposable class when creating the UI layer.
  • Add the disposable object returned by the subscription to our manager.
  • Clear the subscription object when the UI layer is destroyed.

Instantiate when creating the UI#

@Override
   public void onStart() {
       if (mSubscriptions == null) {
           mSubscriptions = new CompositeDisposable();
       }
   }

Add disposable object#

netWork.getInstance().getDataService()
                .translateYouDao(q,from,to,appID,salt,sign,signType,curtime)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TranslationBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mSubscriptions.add(d);   // Add to the container here
                    }

                    @Override
                    public void onNext(TranslationBean translationBean) {
                        List<TranslationBean> list_word = new ArrayList<>();
                        list_word.add(translationBean);
                        mView.showResult(list_word);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showConnection();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

Unsubscribe when the UI layer is destroyed#

@Override
    public void onDestroy() {
        if (mSubscriptions != null) {
            mSubscriptions.dispose();
            mSubscriptions.clear();
            mSubscriptions = null;
        }
    }

Summary#

I didn't notice some details myself, so I still need to look at other people's code more. The class that I don't know what it is used for may be the place I ignored.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.