Is it recommended to call Disposable.dispose() as soon as a subscription completes work?

前端 未结 2 978
孤城傲影
孤城傲影 2021-01-01 22:54

I have an Activity in which I\'m creating and subscribing to multiple instances of the Single class (each doing some work in a separate background

2条回答
  •  渐次进展
    2021-01-01 23:15

    Yosriz's answer is the correct answer but if you do want remove Disposable instances from your CompositeDisposable instance as the Single subscriptions complete work (and not have the Disposable instances hang around), then I've put together this class...

    public abstract class MySingleObserver implements SingleObserver {
    
        private Disposable disposable;
    
        @Override
        public void onSubscribe(@NonNull Disposable disposable) {
            this.disposable = disposable;
            onStart();
        }
    
        public Disposable getDisposable() {
            return disposable;
        }
    
        public abstract void onStart();
    }
    

    ... which you can pass in as the SingleObserver to your Single subscriptions as follows:

    Single.just(1)
          .subscribe(new MySingleObserver() {
    
              @Override
              public void onStart() {
                  MyActivity.this.myCompositeDisposable.add(getDisposable());
                  // do something further
              }
    
              @Override
              public void onSuccess(@NonNull Integer success) {
                  MyActivity.this.myCompositeDisposable.remove(getDisposable());
                  // do something further
              }
    
              @Override
              public void onError(@NonNull Throwable error) {
                  MyActivity.this.myCompositeDisposable.remove(getDisposable());
                  // do something further
              }
          });
    

提交回复
热议问题