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