RxSwift源码分析(2)——核心逻辑

RxSwift的核心逻辑很重要,是分析整个框架的基础
希望通俗易通,没有弄思维导图,个人觉得太多对象和线条的思维导图,还没看就眼花。不多说直接奔主题,以Observable开始,重点是核心逻辑,其他细节先忽略。例子:

let observable = Observable.create { (anyObserver) -> Disposable in
    anyObserver.onNext("发送响应")
    anyObserver.onCompleted()
    return Disposables.create()
}
observable.subscribe { (text) in
    print("收到响应")
}.disposed(by: disposbag)
  1. 首先是创建序列:
let observable = Observable.create { (observer) -> Disposable in
    ...
}
  1. 开始进入源码,Observable继承了ObservableType协议(协议方法需要在别的扩展里找到):
public class Observable : ObservableType {
    ...
}

ObservableType实现了create,返回AnonymousObservable(保存了序列闭包subscribeHandler):

extension ObservableType {
    public static func create(_ subscribe: @escaping (AnyObserver) -> Disposable) -> Observable {
        return AnonymousObservable(subscribe)//内部保存了闭包subscribe
    }
}
final private class AnonymousObservable: Producer {
    ...
    init(_ subscribeHandler: @escaping SubscribeHandler) {
        self._subscribeHandler = subscribeHandler
    }
    
}
  1. 然后回到外面进行订阅,也就是AnonymousObservable.subscribe
observable.subscribe { (event) in
    ...
}
  1. AnonymousObservable没有具体的subscribe方法,这时候找父类,然而这里面是层层套,最后能看到它实现了ObservableType协议:
final private class AnonymousObservable: Producer {
    ...  
}
class Producer : Observable {
    ...
}
public class Observable : ObservableType {
    ...
}

具体协议方法里,创建了匿名内部观察者AnonymousObserver(保存了事件闭包eventHandler),返回销毁者:

extension ObservableType {
    ...
public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
        -> Disposable {
            ...
            let observer = AnonymousObserver { event in
               ...
            }
            return Disposables.create(
                self.asObservable().subscribe(observer),
                disposable
            )
    }
    ...
}
final class AnonymousObserver : ObserverBase {
    ...
    init(_ eventHandler: @escaping EventHandler) {
        ...
        self._eventHandler = eventHandler
    }
    ...
}
  1. 在返回销毁者时调用self.asObservable().subscribe,首先是self.asObservable()
public class Observable : ObservableType {
    public func subscribe(_ observer: O) -> Disposable where O.E == E {
        rxAbstractMethod() //具体方法由子类实现
    }

    public func asObservable() -> Observable {
        return self  //子类可能会实现具体方法,最后结果都是返回一个序列Observable
    }
}

然后self.asObservable().subscribe =>
self.subscribe =>
AnonymousObservable.subscribe =>
Producer.subscribe

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
            }
        }
    }
    ...
}
  1. Producer最终会调用self.run,而子类AnonymousObservable实现了具体的run方法:
final private class AnonymousObservable: Producer {
    ...
    override init(observer: O, cancel: Cancelable) {
        super.init(observer: observer, cancel: cancel)
    }

    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)
    }
}
  1. 然后AnonymousObservablerun里面创建了AnonymousObservableSink(业务下沉),保存了这里的observer(即AnonymousObserver)cancelAnonymousObservableSink拥有所有的功能——观察,发送,响应,销毁,相当于manager的作用,然后调用sink.run
final private class AnonymousObservableSink: Sink, ObserverType {
   ...
   override init(observer: O, cancel: Cancelable) {
       super.init(observer: observer, cancel: cancel)
   }
   ...
}
class Sink : Disposable {
    ...
    init(observer: O, cancel: Cancelable) {
        ...
        self._observer = observer
        self._cancel = cancel
    }
    ...
}
  1. sink.run内部的parent便是传进来的AnonymousObservable,然后创建AnyObserver(保存AnonymousObservableSink.on函数),并利用AnonymousObservable保存的序列闭包subscribeHandler发送到外面:
final private class AnonymousObservableSink: Sink, ObserverType {
    ...
    func run(_ parent: Parent) -> Disposable {
        return parent._subscribeHandler(AnyObserver(self))
    }
}
public struct AnyObserver : ObserverType {
    ...
    public init(_ observer: O) where O.E == Element {
        self.observer = observer.on
    }
    ...
}
  1. 外面的_subscribeHandler就会调用anyObserver.onNext(""),而anyObserver就是AnyObserver
let observable = Observable.create { (anyObserver) -> Disposable in
    anyObserver.onNext("发送信号")
    anyObserver.onCompleted()  //发送完成
    return Disposables.create() //销毁者
}
  1. AnyObserver继承了ObserverType协议:
public struct AnyObserver : ObserverType {
    ...
}
extension ObserverType {
    public func onNext(_ element: E) {
        self.on(.next(element))
    }
    ...
}
  1. AnyObserver又具体实现了self.on
public struct AnyObserver : ObserverType {
    ...
    public func on(_ event: Event) {
        return self.observer(event)
    }
    ...
}
  1. 然后调用self.observer,便是AnyObserver保存的AnonymousObservableSink.on
inal private class AnonymousObservableSink: Sink, ObserverType {
    ...
    func on(_ event: Event) {
        ...
        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()
            }
        }
    }
    ...
}
  1. 然后根据event进入.next,调用self.forwardOnAnonymousObservableSink没有具体的forwardOn,找父类Sink
class Sink : Disposable {
    ...
    final func forwardOn(_ event: Event) {
        ...
        if isFlagSet(self._disposed, 1) {
            return
        }
        self._observer.on(event)
    }
    ...
}
  1. self._observer便是AnonymousObservableSink保存的AnonymousObserverAnonymousObserver没有具体的on方法,找父类ObserverBase
final class AnonymousObserver : ObserverBase {
    ...
}
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)
            }
        }
    }
    ...
}
  1. 然后又回到AnonymousObserver.onCore
final class AnonymousObserver : ObserverBase {
    ...
    override func onCore(_ event: Event) {
        return self._eventHandler(event)
    }
    ...
}
  1. self._eventHandler便是AnonymousObserver保存的事件闭包eventHandler
extension ObservableType {
    ...
public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
        -> Disposable {
            ...
            let observer = AnonymousObserver { event in
               ...
                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
            )
    }
    ...
}
  1. 最后根据event调用外面传进来的onNext?(value),便回到最初外面的响应闭包:
observable.subscribe { (text) in
    print("收到响应")
}.disposed(by: disposbag)

这样才能基本完成一个订阅响应的流程,还是不懂的可以自己断点慢慢走一遍。

你可能感兴趣的:(RxSwift源码分析(2)——核心逻辑)