在RxSwift中处理一次性可观察对象的正确方法 [英] 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:
使用处置袋或takeUntil运算符是确保清理资源的有效方法.即使序列会在有限的时间内终止,我们还是建议在生产中使用它们.
Using dispose bags or takeUntil operator is a robust way of making sure resources are cleaned up. 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(...))
}
}
}
说我不希望取消此可观察对象的订阅者,我只希望它运行一次并完成.我希望该可观察对象的生命周期在工作本身完成时结束.意味着我看不到有适合disposeBag的好的候选人. takeUntil也期望发生事件",而且我看不到任何好的事件.
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. Meaning there are no good candidates for disposeBag that I can see. takeUntil also expects an 'event', and there are no good ones that I can see.
现在,我只是通过丢弃一次性用品来解决警告:
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?
推荐答案
DiposeBag
和takeUntil
都用于取消预订在之前接收到.Completed/.Error
事件的预订.
Both DiposeBag
and takeUntil
are used to cancel a subscription prior to receiving the .Completed/.Error
event.
Observable
完成后,用于管理订阅的所有资源都会自动处置.
When an Observable
completes, all the resources used to manage subscription are disposed of automatically.
As of RxSwift 2.2, You can witness an example of implementation for this behavior in 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()
}
}
}
在转发事件后,在接收到.Error
或.Completed
事件时,查看AnonymousObservableSink
调用如何自行处理.
See how AnonymousObservableSink
calls dispose on itself when receiving either an .Error
or a .Completed
event, after forwarding the event.
最后,对于此用例,_ =
是可行之路.
In conclusion, for this use case, _ =
is the way to go.
这篇关于在RxSwift中处理一次性可观察对象的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!