iOS框架 - RXSwift原理初探

前言

RXSwift是一个使用可观察序列和函数式操作符编写异步和基于事件的代码的库。今天我们从一个简单的例子出发,来简单探究下其中的原理。

RXSwift简单使用

let ob = Observable.create { (obserber) -> Disposable in
            // 3:发送信号
            obserber.onNext("消息来了")
            obserber.onCompleted()
//            obserber.onError(NSError.init(domain: "coocieeror", code: 10087, userInfo: nil))
            return Disposables.create()
        }
let _ = ob.subscribe(onNext: { (text) in
            print("订阅到:\(text)")
        }, onError: { (error) in
            print("error: \(error)")
        }, onCompleted: {
            print("完成")
        }) {
            print("销毁")
        }

Observable.create初始化

Observablesequence,Observable表示可监听或者可观察的序列。
首先我们来看下.create到底做了啥:

public static func create(_ subscribe: @escaping (AnyObserver) -> Disposable) -> Observable {
        return AnonymousObservable(subscribe)
    }

在Create.h文件找到.create方法,可以看出返回的是一个AnonymousObservable初始化的序列。

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)
    }
}

此处AnonymousObservable的初始化工作只是将.create方法带进来的闭包作为属性保存下来。

subscribe订阅

接着我们拉到了subscribe方法中:

extension ObservableType {
    public func subscribe(_ on: @escaping (Event) -> Void)
        -> Disposable {
            let observer = AnonymousObserver { e in
                on(e)
            }
            return self.asObservable().subscribe(observer)
    }
    
    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
            )
    }
}

其中生成一个观察者observer(AnonymousObserver类型),初始化过程中也是将后面闭包作为属性保存下来留给后面调用时候使用。
最后self.asObservable().subscribe(observer),将observer作为参数带入.subscribe,那么.subscribe方法在哪里呢?
我们来看self.asObservable(),此处的selfAnonymousObservable,但在上面AnonymousObservable源码中没看见,但是它继承自Producer,查看Producer源码:

class Producer : Observable {
    override init() {
        super.init()
    }

    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
            }
        }
    }

    func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
        rxAbstractMethod()
    }
}

可知,.subscribe方法是从Producer继承过来的,查看.subscribe方法,其中self.run(observer, cancel: disposer),调用自己的run方法,接着查看AnonymousObservable源码中的.run方法:

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)
    }

run方法中生成一个AnonymousObservableSink类型的对象,我们称之为管子,那这个所谓的管子是干嘛的呢?

AnonymousObservableSink 管子

从上面的run方法中看出,AnonymousObservableSink初始化中将之前subscribe方法中的observer(观察者)和cancel(销毁者)作为属性保存进去:

//AnonymousObservableSink
override init(observer: O, cancel: Cancelable) {
        super.init(observer: observer, cancel: cancel)
    }
//Sink
fileprivate let _observer: O
fileprivate let _cancel: Cancelable

init(observer: O, cancel: Cancelable) {
#if TRACE_RESOURCES
        _ = Resources.incrementTotal()
#endif
        self._observer = observer
        self._cancel = cancel
    }

接着调用AnonymousObservableSink.run方法,并且将自身带进去:

//typealias Parent = AnonymousObservable
func run(_ parent: Parent) -> Disposable {
        return parent._subscribeHandler(AnyObserver(self))
    }

其中Parent即为AnonymousObservable,此时sink里面已经获取到了observer(观察者)、cancel(销毁者)、obserberable(序列),即sink拥有了RXSwift最关键的三要素
然后调用之前初始化保存的_subscribeHandler闭包,将AnyObserver(self)作为参数。那为啥这里是传入的AnyObserver(self),看起来像是将self(AnonymousObservableSink)包装了一层,查看AnyObserver源码,初始化函数为

public typealias EventHandler = (Event) -> Void
private let observer: EventHandler
public init(_ observer: O) where O.E == Element {
        self.observer = observer.on
    }

初始化方法中参数observer即为AnonymousObservableSink,然后将AnonymousObservableSink.on给到self.observer,此时AnyObserver.observer为一个函数块。查看此时AnonymousObservableSink中的on方法:

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()
            }
        }
    }

sink.on方法中看起来像是是对我们外部订阅者的事件调用,不急,慢慢来,现在我们需要看的是我们的猜想是不是正确的,回到_subscribeHandler(AnyObserver(self))这句代码,可知是将AnyObserver类型作为外界.create后闭包中参数obserber的类型,那是不是obserber.onNext()就应该去AnyObserver中去找?
首先在AnyObserver中没找到.onNext()方法,但AnyObserver遵守了OberverType协议,

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方法self.on(.next(element)),即回到AnyObserver中的.on方法:

public func on(_ event: Event) {
        return self.observer(event)
    }

即将当前的具体任务event(.next(element))作为参数放进self.observer(一个函数块)去执行,即又回到了AnonymousObservableSink.on方法,针对不同订阅事件都回去调用self.forwardOn(event),此时来到了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即为sink(管子)初始化时候保存下来的观察者,即AnonymousObserver,由此可以看出,为啥叫“管子”了吧,它是将订阅者和观察者连在一起的这么一种中间工具。

AnonymousObserver继承自ObserverBase,在ObserverBase中找到了.on方法:

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)
            }
        }
    }

回到AnonymousObserver中找到.onCore方法:

override func onCore(_ event: Event) {
        return self._eventHandler(event)
    }

所以一切就回到了AnonymousObservable.subscribe()方法中生成observer(AnonymousObserver)保存的闭包:

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()
                }

最终对应的事件做对应的处理。断点打印此时的event:


总结

RXSwift流程图

本文通过逐步查看 RxSwift 中的部分源码,一窥其背后的设计思路。从中我们也看到了其对函数式编程的应用,以及其所呈现出来的流编程模式的底层实现原理。

你可能感兴趣的:(iOS框架 - RXSwift原理初探)