When creating an Observable like this:
public void foo() {
Observable observable = Observable.fromCallable(() -> {
bar();
return "";
})
.doOnSubscribe(disposable -> System.out.println("onSubscribe"))
.doOnDispose(() -> System.out.println("onDispose"));
Disposable disposable = observable.subscribe();
disposable.dispose();
}
private void bar() {
System.out.println("bar");
}
doOnSubcribe is called, doOnDispose is not called.
Why is that?
You need to use the doFinally() operator.
doOnDispose() has a very narrow use case, where the observable is explicitly disposed. In your example, the observable terminates "naturally" by onComplete(). By the time that you call dispose(), the observable is done, and nothing will happen -- disposing a completed observable has no effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With