RxSwiftswift

RxSwift调度者-scheduler源码解析(下)

2019-07-31  本文已影响279人  Cooci_和谐学习_不急不躁

这一篇关于调度的具体流程分析,如有对RxSwift调度者不太了解的观客,请移步RxSwift调度者-scheduler源码解析(上)

observeOn&subscribeOn

上面两个函数是 RxSwift 切换调度环境非常重要的,可以说掌握了这两个函数对 RxSwift调度者 的理解可谓是:指日可待

首先我给大家带来一个测试:

DispatchQueue.global().async {
    self.actionBtn.rx.tap
        .subscribe(onNext: { () in
            print("点击了按钮 --- \(Thread.current)")
        })
        .disposed(by: self.bag)
}
image
public func controlEvent(_ controlEvents: UIControl.Event) -> ControlEvent<()> {
    let source: Observable<Void> = Observable.create { [weak control = self.base] observer in
            // 调度主线程判断
            MainScheduler.ensureRunningOnMainThread()
        }
    return ControlEvent(events: source)
}
public init<Ev: ObservableType>(events: Ev) where Ev.Element == Element {
    self._events = events.subscribeOn(ConcurrentMainScheduler.instance)
}

public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable {
    return self._events.subscribe(observer)
}
public func subscribeOn(_ scheduler: ImmediateSchedulerType)
    -> Observable<Element> {
    return SubscribeOn(source: self, scheduler: scheduler)
}
final private class SubscribeOn<Ob: ObservableType>: Producer<Ob.Element> {
    let source: Ob
    let scheduler: ImmediateSchedulerType
    
    init(source: Ob, scheduler: ImmediateSchedulerType) {
        self.source = source
        self.scheduler = scheduler
    }
    
    override func run(_ observer: cancel:) -> (sink:subscription:) {
        let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel)
        let subscription = sink.run()
        return (sink: sink, subscription: subscription)
    }
}
func run() -> Disposable {
    let disposeEverything = SerialDisposable()
    let cancelSchedule = SingleAssignmentDisposable()
    
    disposeEverything.disposable = cancelSchedule
    
    let disposeSchedule = self.parent.scheduler.schedule(()) {

        let subscription = self.parent.source.subscribe(self)
        disposeEverything.disposable = ScheduledDisposable(scheduler: disposable:)
        return Disposables.create()
    }
    cancelSchedule.setDisposable(disposeSchedule)
    return disposeEverything
}
func schedule<StateType>(_ state: action: ) -> Disposable {
    let cancel = SingleAssignmentDisposable()
    self.queue.async {
        if cancel.isDisposed {
            return
        }
        cancel.setDisposable(action(state))
    }
    return cancel
}
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()
        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
        }
    }
}
public func schedule<StateType>(_ state: action: ) -> Disposable {

    if CurrentThreadScheduler.isScheduleRequired {
      // 已经标记,就置false
        CurrentThreadScheduler.isScheduleRequired = false
     // 外界闭包调用执行
        let disposable = action(state)
      // 延迟销毁 
        defer {
            CurrentThreadScheduler.isScheduleRequired = true
            CurrentThreadScheduler.queue = nil
        }
      // 先省略。。。
        return disposable
    }
     // 先省略。。。
    return scheduledItem
}
public func scheduleRecursive<State>(_ state: action: ) -> Disposable {
    // 递归调度者
    let recursiveScheduler = RecursiveImmediateScheduler(action: scheduler:)
    // 调度状态执行
    recursiveScheduler.schedule(state)
    return Disposables.create(with: recursiveScheduler.dispose)
}
func schedule(_ state: State) {
    var scheduleState: ScheduleState = .initial
    let d = self._scheduler.schedule(state) { state -> Disposable in     
        // 这里因为在递归环境,加了一把锁递归锁,保障安全   
        let action = self._lock.calculateLocked { () -> Action? in
                 return self._action
        }
        
        if let action = action {
            action(state, self.schedule)
        }
        
        return Disposables.create()
    }
  // 篇幅,先省略,大家自行查阅  
}
public func schedule<StateType>(_ state: StateType, action: ) -> Disposable {
    // 上面的流程就省略了
    let existingQueue = CurrentThreadScheduler.queue

    let queue: RxMutableBox<Queue<ScheduledItemType>>
    if let existingQueue = existingQueue {
        queue = existingQueue
    }
    else {
        queue = RxMutableBox(Queue<ScheduledItemType>(capacity: 1))
        CurrentThreadScheduler.queue = queue
    }

    let scheduledItem = ScheduledItem(action: action, state: state)
    queue.value.enqueue(scheduledItem)

    return scheduledItem
}
public func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
    if CurrentThreadScheduler.isScheduleRequired {

        CurrentThreadScheduler.isScheduleRequired = false
        let disposable = action(state)  

         // 判断当前队列情况,是否存在
        guard let queue = CurrentThreadScheduler.queue else {
            return disposable
        }
        // 从队列去除任务
        while let latest = queue.value.dequeue() {
            if latest.isDisposed {
                continue
            }
            latest.invoke()
        }

        return disposable
    }
    /// 省略
}
func invoke() {
     self._disposable.setDisposable(self._action(self._state))
}
override func onCore(_ event: Event<Element>) {
    let shouldStart = self._lock.calculateLocked { () -> Bool in
        self._queue.enqueue(event)
    }
    if shouldStart {
        self._scheduleDisposable.disposable = 
        self._scheduler.scheduleRecursive((), action: self.run)
    }
}
func run(_ state: (), _ recurse: (()) -> Void) {
    // 加锁获取观察者,很队列任务
    let (nextEvent, observer) = self._lock.calculateLocked { 
        if !self._queue.isEmpty {
            return (self._queue.dequeue(), self._observer)
        }
    }
   
    // 观察者发送响应
    if let nextEvent = nextEvent, !self._cancel.isDisposed {
        observer.on(nextEvent)
        if nextEvent.isStopEvent {
            self.dispose()
        }
    }
}

完美!解析到这里,整个流程解析完毕,就问此时此刻还有谁?
45度仰望天空,该死!我这无处安放的魅力!

总结

整个流程是比较复杂,其实如果你这个时候,整体看源码(上帝的视角)!不难得出:

就是两层序列订阅响应,我的第二层的 sink 就是源序列的观察者

RxSwift的源码其实你只要掌握我前面的分享过的核心逻辑,后面的内容都是一样的,只不过嵌套,胶水代码依赖建立。其中依赖关系,中间层封装,流程走位是各位在接下来的iOS进阶非常重要的思维,告别垃圾代码,迎接未来!我们一起加油:和谐学习,不急不躁

上一篇 下一篇

猜你喜欢

热点阅读