阅读 173

RxSwift核心逻辑

前言

RxSwift是一套函数响应式编程框架,核心就是可观察序列Observable Observable有两种,即有穷序列 (比如网络请求) 和无穷序列 (比如timer)

Observable生命周期 1、创建序列:Observable.create 2、订阅信号:obserber.subscribe 3、发送信号:如下图👇

Observale生命周期

下面,我们来看下它是怎么创建、订阅和发送的(划重点,考试要考(^-^)V)

//1、创建序列
let ob = Observable<Any>.create { (obserber) -> Disposable in
   //3、发送订信号
   obserber.onNext("hello")
   obserber.onCompleted()
   return Disposables.create()
}

//2、订阅信号
ob.subscribe(onNext: { (value) in
   //4、收到
   print("订阅\(value)")
}, onError: { (error) in
   print("错误")
}, onCompleted: {
   print("完成")
}) {
   print("销毁")
}
复制代码

这里有两个重点,2 --> 3,3 --> 4 2 --> 3实际上,只需要看到AnonymousObservable._subscribeHandler(observer)

1、我们首先来看下创建序列,找到Observable.create源码

public static func create(_ subscribe: @escaping (AnyObserver<Element>) -> Disposable) -> Observable<Element> {
        return AnonymousObservable(subscribe)
}
复制代码

可以看到返回了AnonymousObservable(subscribe),跟进去

//注意AnonymousObservable继承于Producer
final private class AnonymousObservable<Element>: Producer<Element> {
    typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable

    let _subscribeHandler: SubscribeHandler

    init(_ subscribeHandler: @escaping SubscribeHandler) {
        //保存subscribe,即AnonymousObservable._subscribeHandler(),后续self._subscribeHandler()
        self._subscribeHandler = subscribeHandler
    }

    //父类的方法,先不管暂停,这里还没调用
    override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
        let sink = AnonymousObservableSink(observer: observer, cancel: cancel)
        let subscription = sink.run(self)
        return (sink: sink, subscription: subscription)
    }
}
复制代码

2、接下来我们看下订阅subscribe,上源码

public func subscribe(onNext: ((Element) -> 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() : []
            
            //从这里看起,这里创建了一个AnonymousObserver作为参数,也就是说,之后只需要observe.onNext(xxx)
            let observer = AnonymousObserver<Element> { 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(
                //asObservable()就是observable,也就是说调用了之前在AnonymousObservable保存的self._subscribeHandler(),即ob.subscribe(observer),最终找到Product里面的subscribe
                self.asObservable().subscribe(observer),
                disposable
            )
    }
复制代码

Producer

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

  //subscribe函数
    override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
        if !CurrentThreadScheduler.isScheduleRequired {
            // The returned disposable needs to release all references once it was disposed.
            let disposer = SinkDisposer()
             //看这里,调用了子类的run
            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: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
        rxAbstractMethod()
    }
}
复制代码

我们再回头看下这段代码

//父类的方法,先不管暂停,这里还没调用
//现在到这里来了
    override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
        let sink = AnonymousObservableSink(observer: observer, cancel: cancel)
        //run,即AnonymousObservable._subscribeHandler(AnyObserver(self))
        let subscription = sink.run(self)
        return (sink: sink, subscription: subscription)
    }
复制代码

到这里,2 --> 3解决了

3、发送信号

这就简单了,看subscribe函数就行了


梳理下

RxSwift核心逻辑.png

关注下面的标签,发现更多相似文章
评论