Do I need to check isDisposed() before calling dispose()?
Asked Answered
D

4

15

I'm learning RxJava and I noticed a lot of the sample code does a isDisposed() check before calling dispose(). I did not notice any issues when I called dispose() on an already disposed Disposable.

So my question is, do I need the isDisposed() check? Are there situations where I should check isDisposed() before disposing? What are the pros and cons on doing the check first?

Downall answered 11/4, 2018 at 9:54 Comment(0)
A
17

It makes little sense to call isDisposed. dispose implementations already do that for you and make sure repeated calls are no-ops or have no detectable effect.

Unfortunately, somebody in the early days of RxJava started writing examples with it and now everybody keeps copying that pattern.

It makes a little more sense to check isDisposed before calling onNext for example but you don't get to do that very often outside Observable.create().

Algophobia answered 11/4, 2018 at 10:13 Comment(2)
When does it make sense to check isDisposed before calling onNext and why? -- I've found code which calls it every time when using Single.create etc. , is it possible to abuse a single in any way to make it be disposed and then try to make it emit something? What happens if you don't check for isDisposed in these cases?Osman
@SimonForsberg Depends on what the sequence does in your found code. Maybe they have a create-dispose race and want to avoid undeliverable exceptions by doing eager isDispose checks.Algophobia
J
2

I don't think so. If you check for example the implementation of CompositeDisposable,

     @Override
        public void dispose() {
            if (disposed) {
                return;
            }
    ...rest of method body
    @Override
        public boolean isDisposed() {
            return disposed;
        }
Jepson answered 11/4, 2018 at 10:15 Comment(0)
O
0

dispose is basically for closing the stream of your subscription. you're checking isdisposed() will tell you if the existing stream is active. if any relevant data passing through that stream it will be cut.

Ofcors, you can call dispose anytime.

Ollayos answered 12/4, 2018 at 13:40 Comment(0)
R
-1

what about safeDispose?

fun Disposable?.safeDispose() {
    if (this?.isDisposed == false) {
        dispose()
    }
}
Rebane answered 16/2, 2021 at 15:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.