Skip to content
Advertisement

Why is doOnDispose not called?

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?

Advertisement

Answer

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.

Advertisement