Why is doOnDispose not called?
Asked Answered
P

1

15

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?

Plonk answered 7/3, 2018 at 14:16 Comment(0)
C
36

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.

Commutative answered 7/3, 2018 at 14:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.