When should we call addDisposableTo(disposeBag) in RxSwift?

﹥>﹥吖頭↗ 提交于 2019-12-10 01:33:52

问题


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("🔴")
    .subscribe { event in
        print(event)
    }
    .addDisposableTo(disposeBag)

Should I have to .addDisposableTo(disposeBag) explicitly? I think after sending "🔴", the Observable will terminate and releasing the observer?


回答1:


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




回答2:


Dispose bags are used to return ARC like behavior to RX. When a DisposeBag is deallocated, it will call dispose on each of the added disposables.

It is used to dispose of old references that you pass in the closure and resources that are not needed anymore(and which were apparently not used): for example an open HTTP connection, a database connection or a cache.

So if we have any resources that can be left, you should call it.

More in this article.



来源:https://stackoverflow.com/questions/37724766/when-should-we-call-adddisposabletodisposebag-in-rxswift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!