Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 465
idunnololz Avatar asked Apr 11 '18 09:04

idunnololz


2 Answers

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().

like image 194
akarnokd Avatar answered Sep 28 '22 00:09

akarnokd


I don´t think so, if you check i.e. implementation of CompositeDisposable(of course if you using that class, not another implementation of disposable interface) there is :

 @Override
    public void dispose() {
        if (disposed) {
            return;
        }
...rest of method body
@Override
    public boolean isDisposed() {
        return disposed;
    }

So the answer is it depends in what way Disposable interface is implemented, You can check it in JetBrains IDE by right click and go to> implementation

like image 26
Bartosz Avatar answered Sep 27 '22 23:09

Bartosz