[英]When should we 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. 我们创建一个
DisposeBag
,一个Observable
,订阅Observable
然后addDisposableTo(disposeBag)
,我知道当DisposeBag
要去掉时,它会调用dispose()
释放资源,否则会导致内存泄漏。
If the Observable
send Complete
or Error
that terminate in finite time. 如果
Observable
发送在有限时间内终止的Complete
或Error
。 When the Observable
terminate before DisposeBag
deinit, do I have the need to call addDisposableTo(disposeBag)
? 当
Observable
在DisposeBag
deinit之前终止时,我是否需要调用addDisposableTo(disposeBag)
? Does DisposeBag
automatically release the observer that subscribed to it when it received terminated message? DisposeBag
在收到终止消息时会自动释放订阅它的观察者吗?
let disposeBag = DisposeBag()
Observable.just("🔴")
.subscribe { event in
print(event)
}
.addDisposableTo(disposeBag)
Should I have to .addDisposableTo(disposeBag)
explicitly? 我应该明确地使用
.addDisposableTo(disposeBag)
吗? I think after sending "🔴", the Observable
will terminate and releasing the observer? 我想在发送“🔴”之后,
Observable
将终止并释放观察者?
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. 如果你确信以确定的方式可观察到的完成-就像使用
just
在你的榜样,或者使用take
, takeUntil
等- ,你可以选择不使用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.
但总的来说,如果你使用DisposeBag,它会更具前瞻性。
See: Unused disposable warning 请参阅: 未使用的一次性警告
Dispose bags are used to return ARC like behavior to RX. 处理袋用于将类似ARC的行为返回到RX。 When a DisposeBag is deallocated, it will call dispose on each of the added disposables.
当DisposeBag被取消分配时,它将在每个添加的一次性用品上调用dispose。
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. 它用于处理您在闭包中传递的旧引用和不再需要的资源(显然不使用它们):例如,打开HTTP连接,数据库连接或缓存。
So if we have any resources that can be left, you should call it. 因此,如果我们有任何可以留下的资源,你应该调用它。
More in this article . 更多内容来自本文 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.