Magren

Magren

Idealist & Garbage maker 🛸
twitter
jike

CompositeDisposable in RxJava

When I was studying RxJava, I found that I had missed some knowledge points and was not rigorous enough. Here, I will add another knowledge point. That is the CompositeDisposable class.

When using RxJava with Retrofit, when sending a request and getting the data, we often need to refresh the page to display the data in the view. However, if the network is slow and the data is returned slowly, and we quickly close the current activity, RxJava will throw a NullPointerException when trying to refresh the interface after receiving the returned data. In other words, if our UI layer is destroyed during the request process and the subscription is not canceled in time, it will cause memory leaks. This is where our CompositeDisposable comes in.

Usage#

The usage is roughly three steps:

  • When creating the UI layer, instantiate our CompositeDisposable class.
  • 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 it 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, 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.