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

前端 未结 2 965
孤城傲影
孤城傲影 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<T> implements SingleObserver<T> {
    
        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<Integer>() {
    
              @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
              }
          });
    
    0 讨论(0)
  • 2021-01-01 23:17

    No, you shouldn't.When an Observable is completed, Observable is disposed of by itself.
    This is part of the Observable contract:

    When an Observable issues an OnError or OnComplete notification to its observers, this ends the subscription. Observers do not need to issue an Unsubscribe notification to end the subscriptions that are ended by the Observable in this way.

    0 讨论(0)
提交回复
热议问题