RxSwift的核心逻辑很重要,是分析整个框架的基础。
希望通俗易通,没有弄思维导图,个人觉得太多对象和线条的思维导图,还没看就眼花。不多说直接奔主题,以Observable开始,重点是核心逻辑,其他细节先忽略。例子:
let observable = Observable<Any>.create { (anyObserver) -> Disposable in
anyObserver.onNext("发送响应")
anyObserver.onCompleted()
return Disposables.create()
}
observable.subscribe { (text) in
print("收到响应")
}.disposed(by: disposbag)
- 首先是创建序列:
let observable = Observable<Any>.create { (observer) -> Disposable in
...
}
- 开始进入源码,
Observable
继承了ObservableType
协议(协议方法需要在别的扩展里找到):
public class Observable<Element> : ObservableType {
...
}
ObservableType
实现了create
,返回AnonymousObservable
(保存了序列闭包subscribeHandler
):
extension ObservableType {
public static func create(_ subscribe: @escaping (AnyObserver<E>) -> Disposable) -> Observable<E> {
return AnonymousObservable(subscribe)//内部保存了闭包subscribe
}
}
final private class AnonymousObservable<Element>: Producer<Element> {
...
init(_ subscribeHandler: @escaping SubscribeHandler) {
self._subscribeHandler = subscribeHandler
}
}
- 然后回到外面进行订阅,也就是
AnonymousObservable.subscribe
:
observable.subscribe { (event) in
...
}
-
AnonymousObservable
没有具体的subscribe
方法,这时候找父类,然而这里面是层层套,最后能看到它实现了ObservableType
协议:
final private class AnonymousObservable<Element>: Producer<Element> {
...
}
class Producer<Element> : Observable<Element> {
...
}
public class Observable<Element> : 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<E> { event in
...
}
return Disposables.create(
self.asObservable().subscribe(observer),
disposable
)
}
...
}
final class AnonymousObserver<ElementType> : ObserverBase<ElementType> {
...
init(_ eventHandler: @escaping EventHandler) {
...
self._eventHandler = eventHandler
}
...
}
- 在返回销毁者时调用
self.asObservable().subscribe
,首先是self.asObservable()
public class Observable<Element> : ObservableType {
public func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
rxAbstractMethod() //具体方法由子类实现
}
public func asObservable() -> Observable<E> {
return self //子类可能会实现具体方法,最后结果都是返回一个序列Observable
}
}
然后self.asObservable().subscribe
=>
self.subscribe
=>
AnonymousObservable.subscribe
=>
Producer.subscribe
class Producer<Element> : Observable<Element> {
...
override func subscribe<O : ObserverType>(_ 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
}
}
}
...
}
-
Producer
最终会调用self.run
,而子类AnonymousObservable
实现了具体的run
方法:
final private class AnonymousObservable<Element>: Producer<Element> {
...
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
override func run<O : ObserverType>(_ 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
的run
里面创建了AnonymousObservableSink
(业务下沉),保存了这里的observer(即AnonymousObserver)
和cancel
,AnonymousObservableSink
拥有所有的功能——观察,发送,响应,销毁,相当于manager的作用,然后调用sink.run
final private class AnonymousObservableSink<O: ObserverType>: Sink<O>, ObserverType {
...
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
...
}
class Sink<O : ObserverType> : Disposable {
...
init(observer: O, cancel: Cancelable) {
...
self._observer = observer
self._cancel = cancel
}
...
}
-
sink.run
内部的parent
便是传进来的AnonymousObservable
,然后创建AnyObserver
(保存AnonymousObservableSink.on
函数),并利用AnonymousObservable
保存的序列闭包subscribeHandler
发送到外面:
final private class AnonymousObservableSink<O: ObserverType>: Sink<O>, ObserverType {
...
func run(_ parent: Parent) -> Disposable {
return parent._subscribeHandler(AnyObserver(self))
}
}
public struct AnyObserver<Element> : ObserverType {
...
public init<O : ObserverType>(_ observer: O) where O.E == Element {
self.observer = observer.on
}
...
}
- 外面的
_subscribeHandler
就会调用anyObserver.onNext("")
,而anyObserver
就是AnyObserver
:
let observable = Observable<Any>.create { (anyObserver) -> Disposable in
anyObserver.onNext("发送信号")
anyObserver.onCompleted() //发送完成
return Disposables.create() //销毁者
}
-
AnyObserver
继承了ObserverType
协议:
public struct AnyObserver<Element> : ObserverType {
...
}
extension ObserverType {
public func onNext(_ element: E) {
self.on(.next(element))
}
...
}
-
AnyObserver
又具体实现了self.on
:
public struct AnyObserver<Element> : ObserverType {
...
public func on(_ event: Event<Element>) {
return self.observer(event)
}
...
}
- 然后调用
self.observer
,便是AnyObserver
保存的AnonymousObservableSink.on
:
inal private class AnonymousObservableSink<O: ObserverType>: Sink<O>, ObserverType {
...
func on(_ event: Event<E>) {
...
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()
}
}
}
...
}
- 然后根据
event
进入.next
,调用self.forwardOn
,AnonymousObservableSink
没有具体的forwardOn
,找父类Sink
:
class Sink<O : ObserverType> : Disposable {
...
final func forwardOn(_ event: Event<O.E>) {
...
if isFlagSet(self._disposed, 1) {
return
}
self._observer.on(event)
}
...
}
-
self._observer
便是AnonymousObservableSink
保存的AnonymousObserver
,AnonymousObserver
没有具体的on
方法,找父类ObserverBase
:
final class AnonymousObserver<ElementType> : ObserverBase<ElementType> {
...
}
class ObserverBase<ElementType> : Disposable, ObserverType {
...
func on(_ event: Event<E>) {
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
:
final class AnonymousObserver<ElementType> : ObserverBase<ElementType> {
...
override func onCore(_ event: Event<Element>) {
return self._eventHandler(event)
}
...
}
-
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<E> { 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
)
}
...
}
- 最后根据
event
调用外面传进来的onNext?(value)
,便回到最初外面的响应闭包:
observable.subscribe { (text) in
print("收到响应")
}.disposed(by: disposbag)
这样才能基本完成一个订阅响应的流程,还是不懂的可以自己断点慢慢走一遍。