[英]Proper way to dispose a one-off observable in RxSwift
I have an observable that I only want to kick off once. 我有一个观察,我只想开始一次。 The docs say:
文档说:
Using dispose bags or takeUntil operator is a robust way of making sure resources are cleaned up.
使用配置袋或takeUntil操作员是确保清理资源的有效方法。 We recommend using them in production even if the sequences will terminate in finite time.
我们建议在生产中使用它们,即使序列将在有限时间内终止。
My observable terminates after just one event 我的观察结果在一次事件后终止
let observable = Observable.create() { observer in
webservice.makeHTTPRequestWithCompletionBlock {
if something {
observer.on(.Next(...))
observer.onCompleted()
} else {
observer.on(.Error(...))
}
}
}
Say I wasn't interested in cancelling subscribers to this observable, I just want it run once and complete. 假设我对取消此观察者的订阅者不感兴趣,我只想让它运行一次并完成。 I want the lifecycle of this observable to end when the work itself is completed.
我希望这个observable的生命周期在工作本身完成时结束。 Meaning there are no good candidates for disposeBag that I can see.
这意味着我无法看到disposeBag的好候选人。 takeUntil also expects an 'event', and there are no good ones that I can see.
takeUntil也期待一个'事件',而且我看不到好的事件。
Right now I just solve the warning by throwing away the disposable: 现在我只是通过丢弃一次性来解决警告:
_ = observeable.subscribeNext { ... }
Is there a way to do this, or a different paradigm that I should use? 有没有办法做到这一点,或者我应该使用不同的范例?
Both DiposeBag
and takeUntil
are used to cancel a subscription prior to receiving the .Completed/.Error
event. DiposeBag
和takeUntil
都用于在接收.Completed/.Error
事件之前取消订阅。
When an Observable
completes, all the resources used to manage subscription are disposed of automatically. 当
Observable
完成时,用于管理订阅的所有资源都将自动处理。
As of RxSwift 2.2, You can witness an example of implementation for this behavior in AnonymousObservable.swift
从RxSwift 2.2开始,您可以在
AnonymousObservable.swift
看到此行为的实现示例
func on(event: Event<E>) {
switch event {
case .Next:
if _isStopped == 1 {
return
}
forwardOn(event)
case .Error, .Completed:
if AtomicCompareAndSwap(0, 1, &_isStopped) {
forwardOn(event)
dispose()
}
}
}
See how AnonymousObservableSink
calls dispose on itself when receiving either an .Error
or a .Completed
event, after forwarding the event. 在转发事件后,在收到
.Error
或.Completed
事件时,查看AnonymousObservableSink
如何调用自身。
In conclusion, for this use case, _ =
is the way to go. 总之,对于这个用例,
_ =
是要走的路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.