网上只有deferred的使用,鲜有其源码流程,因其十分简洁,故详细贴上步骤,如有误,请留言指出,谢谢
let obv_defer = Observable.deferred { () -> Observable in
return Observable.just(1)
}
obv_defer.subscribe(onNext:{
print($0)
}).disposed(by: disposeBag)
贴出关键步骤:
deferred后返回return Deferred(observableFactory: observableFactory)
,保存了工厂闭包,subscribe了AnonymousObserver后,来到deferred的run方法
override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable)
where Observer.Element == Source.Element {
let sink = DeferredSink(observableFactory: self._observableFactory, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
生成一个继承于Sink的DeferredSink,然后sink走run
func run() -> Disposable {
do {
let result = try self._observableFactory()
return result.subscribe(self)
}
catch let e {
self.forwardOn(.error(e))
self.dispose()
return Disposables.create()
}
}
这里是核心,也就是工厂里生成新Observable的时机,执行deferred保存的工厂闭包,拿到闭包返回的Observable,这里是Just(1),由工厂新生成的observable来subscribe自身,也就是deferredSink
override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element {
observer.on(.next(self._element))
observer.on(.completed)
return Disposables.create()
}
来到Just的subscribe方法,on出next后,来到deferredSink的on方法
func on(_ event: Event) {
self.forwardOn(event)
switch event {
case .next:
break
case .error:
self.dispose()
case .completed:
self.dispose()
}
}
forwardOn来到父类Sink
final func forwardOn(_ event: Event) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
if isFlagSet(self._disposed, 1) {
return
}
self._observer.on(event)
}
self._observer就是之前的AnonymousObserver
override func onCore(_ event: Event) {
return self._eventHandler(event)
}
AnonymousObserver只保存了一个闭包,也只有一个onCore方法,走到父类observerBase
func on(_ event: Event) {
switch event {
case .next:
if load(self._isStopped) == 0 {
self.onCore(event)
}
case .error, .completed:
if fetchOr(self._isStopped, 1) == 0 {
self.onCore(event)
}
}
}
onCore后,调用AnonymousObserver的闭包,然后事件闭包onNext调用,走完最开始的print。最后是方法一系列返回,走完Just发送的completed,再一系列返回,走完BinaryDisposable,走完dispose,结束。