Is it recommended to call Disposable.dispose () as soon as the subscription finishes?

I have Activityone in which I create and subscribe to several instances of the class Single(each of which does some work in a separate background thread). For each subscription, I add an instance Disposablecreated for the instance CompositeDisposablethat is bound to Activity. When Activitydestroyed, I call the method CompositeDisposable.clear()to remove all signatures in Activity. This, of course, means that all instances Disposable(including for subscribers who have completed work) hang in mine Activityuntil Activityit is destroyed.

Is this normal, or should I call Disposable.dispose()for each individual subscription every time a particular instance Singleexits (i.e. when it SingleObserverreceives a callback onSuccessor onError)? The problem with the latter approach is that I need to keep track of which ones are Disposableassociated with SingleObserver(which wins the point of use CompositeDisposable). Is there a better approach to distributing a subscription every time an instance Singleshuts down?

+4
source share
2 answers

No, you should not. When completed Observable, it Observableis deleted by itself.
This is part of the observed contract :

Observable OnError OnComplete , . , , .

+7

Yosriz - , Disposable CompositeDrawable Single ( Disposable), ...

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();
}

... SingleObserver Single :

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

Source: https://habr.com/ru/post/1679557/


All Articles