理解函数响应式编程思想
RxSwfit核心内容
- Observable - 产生事件
- Observer - 响应事件
- Operator - 创建变化组合事件
- Disposable - 管理绑定(订阅)的生命周期
- Schedulers - 线程队列调配
按照RxSwfit的说法万物皆序列,所以我们先来探讨Observable序列的产生和Observer监听响应
SimpleCode
let observable = Observable.create { (observer) -> Disposable in
observer.onNext("来了")
observer.onCompleted()
return Disposables.create()
}
let _ = observable.subscribe(onNext: { (text) in
print("订阅到:\(text)")
}, onError: { (error) in
print("error: \(error)")
}, onCompleted: {
print("完成")
}) {
print("销毁")
}
#########
订阅到:来了
完成
销毁
#########
我们关注:
-
create闭包
什么时候执行 -
subscribe闭包
什么时候执行
Observable 继承关系
AnonymousObservable--->Producer--->Observable--->ObservableType--->ObservableConvertibleType
Observer继承关系
AnonymousObserver--->ObserverBase--->Disposable、ObserverType
Sink继承关系
AnonymousObservableSink--->Sink/ObserverType
代码分析
Observable.create
// Create.swift
extension ObservableType {
// MARK: create
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(_ subscribe: @escaping (AnyObserver) -> Disposable) -> Observable {
return AnonymousObservable(subscribe)
}
}
final private class AnonymousObservableSink: Sink, ObserverType {
typealias E = O.E
typealias Parent = AnonymousObservable
// state
private let _isStopped = AtomicInt(0)
#if DEBUG
fileprivate let _synchronizationTracker = SynchronizationTracker()
#endif
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
switch event {
case .next:
if load(self._isStopped) == 1 {
return
}
self.forwardOn(event)
case .error, .completed:
if fetchOr(self._isStopped, 1) == 0 {
self.forwardOn(event)
self.dispose()
}
}
}
func run(_ parent: Parent) -> Disposable {
return parent._subscribeHandler(AnyObserver(self))
}
}
final private class AnonymousObservable: Producer {
typealias SubscribeHandler = (AnyObserver) -> Disposable
let _subscribeHandler: SubscribeHandler
init(_ subscribeHandler: @escaping SubscribeHandler) {
self._subscribeHandler = subscribeHandler
}
override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = AnonymousObservableSink(observer: observer, cancel: cancel)
let subscription = sink.run(self)
return (sink: sink, subscription: subscription)
}
}
Observable.create
在 extension ObservableType
中我们看到create
函数返回一个可观察序列,具体是AnonymousObservable
(匿名可观察序列);
在 class AnonymousObservable
中初始化时传入一个逃逸闭包self._subscribeHandler
,继续找寻看哪里有调用;
在class AnonymousObservableSink
中发现有parent._subscribeHandler(AnyObserver(self))
;
在尾随逃逸闭包处发现传入的参数为AnyObserver,所以进入Observable.subscribe继续探寻。
// ObservableType+Extensions.swift
public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
-> Disposable {
let disposable: Disposable
if let disposed = onDisposed {
disposable = Disposables.create(with: disposed)
}
else {
disposable = Disposables.create()
}
#if DEBUG
let synchronizationTracker = SynchronizationTracker()
#endif
let callStack = Hooks.recordCallStackOnError ? Hooks.customCaptureSubscriptionCallstack() : []
let observer = AnonymousObserver { event in
#if DEBUG
synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { synchronizationTracker.unregister() }
#endif
switch event {
case .next(let value):
onNext?(value)
case .error(let error):
if let onError = onError {
onError(error)
}
else {
Hooks.defaultErrorHandler(callStack, error)
}
disposable.dispose()
case .completed:
onCompleted?()
disposable.dispose()
}
}
return Disposables.create(
self.asObservable().subscribe(observer),
disposable
)
}
Observable.subscribe
临时变量let observer = AnonymousObserver
为观察者,保存闭包AnonymousObserver._eventHandler
;
subscribe
的返回值中有调用self.asObservable().subscribe(observer)
,也就是AnonymousObservable.subscribe(observer)
,根据继承关系,也就是Producer.subscribe(observer)
。
// Producer.swift
// class Producer : Observable
override func subscribe(_ observer: O) -> Disposable where O.E == Element {
if !CurrentThreadScheduler.isScheduleRequired {
// The returned disposable needs to release all references once it was disposed.
let disposer = SinkDisposer()
let sinkAndSubscription = self.run(observer, cancel: disposer)
disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription)
return disposer
}
else {
return CurrentThreadScheduler.instance.schedule(()) { _ in
let disposer = SinkDisposer()
let sinkAndSubscription = self.run(observer, cancel: disposer)
disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription)
return disposer
}
}
}
self.run(observer, cancel: disposer)
,AnonymousObservable
中有重写
// Create.swift
// final private class AnonymousObservable: Producer
override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = AnonymousObservableSink(observer: observer, cancel: cancel)
let subscription = sink.run(self)
return (sink: sink, subscription: subscription)
}
sink.run(self)
,调用到AnonymousObservableSink
类中'run'.
// Create.swift
// final private class AnonymousObservableSink: Sink, ObserverType
func run(_ parent: Parent) -> Disposable {
return parent._subscribeHandler(AnyObserver(self))
}
这里传入的参数并不是我们在Observable.subscribe中创建的observer
,而是AnyObserver(AnonymousObservableSink)
,我们发现AnonymousObservableSink
同时还继承自Sink
,Observable.subscribe中创建的AnonymousObserver
传入了Sink
// Create.swift
// final private class AnonymousObservableSink: Sink, ObserverType
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
// Sink.swift
// class Sink : Disposable
init(observer: O, cancel: Cancelable) {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
self._observer = observer
self._cancel = cancel
}
通过执行parent._subscribeHandler(AnyObserver(self))
此时已经来到了Observable.create尾随逃逸闭包的调用
let observable = Observable.create { (observer) -> Disposable in
observer.onNext("来了")
observer.onCompleted()
return Disposables.create()
}
执行observer.onNext("来了")
或者observer.onCompleted()
// ObserverType.swift
public protocol ObserverType {
/// The type of elements in sequence that observer can observe.
associatedtype E
/// Notify observer about sequence event.
///
/// - parameter event: Event that occurred.
func on(_ event: Event)
}
/// Convenience API extensions to provide alternate next, error, completed events
extension ObserverType {
/// Convenience method equivalent to `on(.next(element: E))`
///
/// - parameter element: Next element to send to observer(s)
public func onNext(_ element: E) {
self.on(.next(element))
}
/// Convenience method equivalent to `on(.completed)`
public func onCompleted() {
self.on(.completed)
}
/// Convenience method equivalent to `on(.error(Swift.Error))`
/// - parameter error: Swift.Error to send to observer(s)
public func onError(_ error: Swift.Error) {
self.on(.error(error))
}
}
这里将onNext(element)
等方法转换成了self.on(.next(element))
,同时上面执行observer.onNext("来了")
或者observer.onCompleted()
的observer
为
AnyObserver(AnonymousObservableSink)
,来到AnonymousObservableSink
我们发现其实现了protocol
方法
// Create.swift
// final private class AnonymousObservableSink: Sink, ObserverType
func on(_ event: Event) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
switch event {
case .next:
if load(self._isStopped) == 1 {
return
}
self.forwardOn(event)
case .error, .completed:
if fetchOr(self._isStopped, 1) == 0 {
self.forwardOn(event)
self.dispose()
}
}
}
继续执行self.forwardOn(event)
// Sink.swift
// class Sink : Disposable
init(observer: O, cancel: Cancelable) {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
self._observer = observer
self._cancel = cancel
}
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
为Observable.subscribe中创建的AnonymousObserver
,所以调用self._observer.on(event)
,为AnonymousObserver.on(event)
,其自身没有实现on
方法
来到其父类的ObserverBase.on
// ObserverBase.swift
// class ObserverBase : Disposable, ObserverType
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)
}
}
}
self.onCore(event)
来到AnonymousObserver.onCore(event)
// AnonymousObserver.swift
// final class AnonymousObserver : ObserverBase {
init(_ eventHandler: @escaping EventHandler) {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
self._eventHandler = eventHandler
}
override func onCore(_ event: Event) {
return self._eventHandler(event)
}
调用self._eventHandler(event)
就来到了Observable.subscribe中闭包的调用
let _ = observable.subscribe(onNext: { (text) in
print("订阅到:\(text)")
}, onError: { (error) in
print("error: \(error)")
}, onCompleted: {
print("完成")
}) {
print("销毁")
}
总结
这个篇幅是探讨RxSwift中Observable可观察序列和Observer观察者的调度流程
①创建可观察序列 Observable
:
产生一个AnonymousObservable
序列,同时把尾随逃逸闭包保存在AnonymousObservable
的self._subscribeHandler
中;
②发起订阅subscribe(onNext: ((Self.E) -> Void)? = nil, onError: ((Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
:
产生一个AnonymousObserver
,通过 ObservableType.asObservable().subscribe(observer)
--->AnonymousObservable.subscribe(observer)
--->Producer.subscribe(observer)
--->AnonymousObservable .run(observer)
--->AnonymousObservableSink .run()
/AnonymousObservableSink (observer)
--->AnonymousObservable._subscribeHandler(AnyObserver(AnonymousObservableSink))
/Sink.init(observer)
--->来到Observable
尾随逃逸闭包的执行/把AnonymousObserver
存入Sink._observer
中;
③信号发送observer.onNext("来了")
:
这里的observer
为AnyObserver(AnonymousObservableSink)
;
observer.onNext(element)
--->AnyObserver.onNext(element)
--->ObserverType.onNext(element)
--->ObserverType.on(.next(element))
--->AnonymousObservableSink.on(.next(element))
--->Sink.forwardOn(event)
--->Sink._observer.on(event)
--->AnonymousObserver.on(event)
--->ObserverBase.on(event)
--->ObserverBase.onCore(event)
--->AnonymousObserver.onCore(event)
--->AnonymousObserver._eventHandler(event)
来到Observable.subscribe中闭包的调用
这里
Sink
在run
之前是Obsevable
的角色后续是Observer
角色