我想编写一个以可以终止它的方式包装observable的函数,并在完成后执行一些代码。我想到了:
class ObsrevableWrapper {
var terminating: Bool = false
var terminatingObservable: Observable<Int>?
func wrapObservable(o: Observable<Int>) -> Observable<Int> {
terminatingObservable = Observable
.deferred { () -> Observable<Int> in
if self.terminating {
return Observable.empty()
} else {
return o
}
}
.takeWhile {_ in
return !self.terminating
}
.publish().refCount()
return terminatingObservable!
}
func terminateObservable() {
terminating = true
terminatingObservable!
.map { _ -> Void in
return ()
}
.ignoreElements()
.concat(Observable.just(()))
.subscribeNext {
self.output("Performing completion code")
}
}
}
我可以在没有var terminating: Bool
实例变量的情况下执行此操作吗? (即功能更强..)