leizh00701 leizh00701 - 5 months ago 155
Swift Question

When we should call addDisposableTo(disposeBag) in RxSwift?

We create a

DisposeBag
, and a
Observable
, subscribe the
Observable
and then
addDisposableTo(disposeBag)
, I know when the
DisposeBag
is going to deinit, it will call
dispose()
to release resources otherwise it will lead memory leak.

If the
Observable
send
Complete
or
Error
that terminate in finite time. When the
Observable
terminate before
DisposeBag
deinit, do I have the need to call
addDisposableTo(disposeBag)
? Does
DisposeBag
automatically release the observer that subscribed to it when it received terminated message?

let disposeBag = DisposeBag()

Observable.just("

Answer

If you are certain that the observable completes in a deterministic way - like using just in your example, or using take, takeUntil, etc. -, you may choose to not use the DisposeBag.

You might get a compiler warning, that actually explains this behavior well and how to work around it. But in general, it is more future-proof if you use DisposeBag anyway.

See: Unused disposable warning

Comments