0

After going through some discussions about when to dispose a CompositeDisposable, I wonder why we can't just add a .dispose() after .subscribe() in code.

Observable.just(0)
    .doOnNext{...}
    .subscribe()
    .dispose()

What is actually happen if the code is like this? Is it ok to write like this? (instead of .addTo(compositeDisposable))

Kone Man
  • 374
  • 1
  • 2
  • 8
  • 2
    not 100% sure but `.dispose()` will kill the subsription so your subscriber will never get called . Use `.dispose()` when you don't want the subscription any more . – Manohar Oct 08 '19 at 16:40
  • 2
    Because it will dispose your flow as soon as subscribe returns, which may or may not give enough time to run an flow with asynchronous steps (before a `subscribeOn` for example). Adding it to a composite will tie it to some lifecycle/scope which will then dispose the flow sometime after. – akarnokd Oct 08 '19 at 18:47
  • @akarnokd I realise that it's true. I experienced the `doOnNext` can still execute because the task is small and complete before being disposed. Adding to `CompositeDisposable` should be the valid way. – Kone Man Oct 09 '19 at 07:32

1 Answers1

0

after you called dispose it will not propagate result to the subscribers anymore

so you should dispose your disposable as soon as this observable stopped to emit values like below

fun Disposable?.disposeIfNotNullAndNotDisposed() {
    if (!(this == null || this.isDisposed)) this.dispose()
}
Zafer Celaloglu
  • 1,438
  • 1
  • 17
  • 28