15

I have a question about the disposal on RxJava. I found this below sentence on RxSwift document on Github.

When a sequence sends the completed or error event all internal resources that compute sequence elements will be freed.

To cancel production of sequence elements and free resources immediately, call dispose on the returned subscription.

if I understand correctly the resources (observables) will be freed after they call onCompleted or onError.

So the question is, does RxJava do the same thing like RxSwift or I need to call the dispose by myself?

Community
  • 1
  • 1
Watcharin.s
  • 604
  • 1
  • 6
  • 18

1 Answers1

21

Yes, all associated resources will be disposed automatically. To illustrate run following test with RxJava 2:

boolean isDisposed = false;

@Test 
public void testDisposed(){
    TestObserver<Integer> to = Observable.<Integer>create(subscriber -> {
        subscriber.setDisposable(new Disposable() {

            @Override
            public boolean isDisposed() {
                return isDisposed;
            }

            @Override
            public void dispose() {
                isDisposed = true;
            }
        });
        subscriber.onComplete();
    }).test();

    to.assertComplete();
    assertTrue(isDisposed);
}
hgrey
  • 3,033
  • 17
  • 21
  • 1
    I'm sure I read somewhere that `.isDisposed()` is not guaranteed to return `true` unless the `.dispose()` method has been explicitly called. IOW an `Observable` can complete and still return `false` for `.isDisposed()`. – Robert Lewis Oct 02 '18 at 14:36
  • 2
    if it disposed automatically why doOnDispose() not called? – Pavel Poley Mar 31 '19 at 16:07
  • Agreed with @RobertLewis I don't think this is guaranteed. Read more : https://github.com/ReactiveX/RxJava/issues/5283 – tir38 Apr 16 '19 at 18:24
  • @PavelPoley You can find the answer here - https://stackoverflow.com/a/49154248/1000551 – Vadim Kotov Apr 16 '20 at 13:37