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