observeOn

Observable.of(3).observeOn(MainScheduler.instance).subscribe {
            print("event  \($0)    \(Thread.current)")
        }.disposed(by: self.disposeBag)
贴出关键步骤

of后返回observableSequence,带着参数elements和currentScheduler,此时调度环境还是of函数中默认的参数scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance在这里也就是MainScheduler。observeOn后,返回observeOnSerialDispatchQueue,带着参数source为observableSequence,和指定的scheduler

//无论串行调度,还是并行调度,都是生成新的序列,在指定调度里走observer回调
public func observeOn(_ scheduler: ImmediateSchedulerType)
        -> Observable {
            if let scheduler = scheduler as? SerialDispatchQueueScheduler {
                return ObserveOnSerialDispatchQueue(source: self.asObservable(), scheduler: scheduler)
            }
            else {
                return ObserveOn(source: self.asObservable(), scheduler: scheduler)
            }
    }
开始subscribe
public func subscribe(_ on: @escaping (Event) -> Void)
        -> Disposable {
            let observer = AnonymousObserver { e in
                on(e)
            }
            return self.asObservable().subscribe(observer)
    }

在这里self还是observeOnserialDispatchQueue,带着AnonymousObserver进行subscribe进入Producer的subscribe方法,

override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element {
        if !CurrentThreadScheduler.isScheduleRequired {
            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
            }
        }
    }

第一次isScheduleRequired为true,调当前线程下schedule方法,里面调用了当前尾随闭包,闭包执行时开始走子类的run方法

override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
        //这个sink直接继承于ObserverBase,并不像其他各种sink继承于Sink
        let sink = ObserveOnSerialDispatchQueueSink(scheduler: self.scheduler, observer: observer, cancel: cancel)
        let subscription = self.source.subscribe(sink)
        return (sink: sink, subscription: subscription)
    }

这个方法里生成了ObserveOnSerialDispatchQueueSink,并让observeOnserialDispatchQueue的source,也就是observableSequence来subscribe它。再次来到observableSequence的父类Producer的subscribe方法,这次isScheduleRequired被置为了false,直接走run方法,但这时的observer参数已经是ObserveOnSerialDispatchQueueSink了,调用run时走到observableSequence方法内的run,走到observableSequenceSink里的run

func run() -> Disposable {
//注意此时observableSequence里_scheduler还是之前那个CurrentThreadScheduler
        return self._parent._scheduler.scheduleRecursive(self._parent._elements.makeIterator()) { 
//原始闭包
iterator, recurse in
            var mutableIterator = iterator
            if let next = mutableIterator.next() {
                self.forwardOn(.next(next))
                recurse(mutableIterator)
            }
            else {
                self.forwardOn(.completed)
                self.dispose()
            }
        }
    }

observableSequence里的scheduler为immediateSchedulerType,走到其extension里的scheduleRecursive方法,参数是一个iterator和一个尾随闭包(原始闭包)

extension ImmediateSchedulerType {
    public func scheduleRecursive(_ state: State, action: @escaping (_ state: State, _ recurse: (State) -> Void) -> Void) -> Disposable {
        let recursiveScheduler = RecursiveImmediateScheduler(action: action, scheduler: self)
        
        recursiveScheduler.schedule(state)
        
        return Disposables.create(with: recursiveScheduler.dispose)
    }
}

RecursiveImmediateScheduler保存了原始闭包,在方法内走RecursiveImmediateScheduler的schedule方法

func schedule(_ state: State) {
        var scheduleState: ScheduleState = .initial

        let d = self._scheduler.schedule(state) { state -> Disposable in
            // R闭包
            if self._group.isDisposed {
                return Disposables.create()
            }
            
            let action = self._lock.calculateLocked { () -> Action? in
                switch scheduleState {
                case let .added(removeKey):
                    self._group.remove(for: removeKey)
                case .initial:
                    break
                case .done:
                    break
                }

                scheduleState = .done

                return self._action
            }
            
            if let action = action {
                action(state, self.schedule)
            }
            
            return Disposables.create()
        }
        
        self._lock.performLocked {
            switch scheduleState {
            case .added:
                rxFatalError("Invalid state")
            case .initial:
                if let removeKey = self._group.insert(d) {
                    scheduleState = .added(removeKey)
                }
                else {
                    scheduleState = .done
                }
            case .done:
                break
            }
        }
    }

方法内先是当前线程schedule方法调用,在currentThreadScheduler里,由于isScheduleRequired还是false,直接走下面scheduledItem的相关方法

public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
        if CurrentThreadScheduler.isScheduleRequired {
            CurrentThreadScheduler.isScheduleRequired = false

            let disposable = action(state)
            // 方法都走过之后回到这里,也就是Producer里那个schedule尾随闭包执行完后
            defer {
                CurrentThreadScheduler.isScheduleRequired = true
                CurrentThreadScheduler.queue = nil
            }

            guard let queue = CurrentThreadScheduler.queue else {
                return disposable
            }

            while let latest = queue.value.dequeue() {
                if latest.isDisposed {
                    continue
                }
                latest.invoke()
            }

            return disposable
        }

        let existingQueue = CurrentThreadScheduler.queue

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

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

        return scheduledItem
    }

scheduledItem保存了RecursiveScheduler里调用schedule方法,self._scheduler.schedule传递的R闭包和elements。方法走完之后,来到
self._lock.performLocked方法,传递进去尾随闭包,performLocked方法内部执行了闭包体,然后方法开始逐层返回

guard let queue = CurrentThreadScheduler.queue else {
                return disposable
            }

            while let latest = queue.value.dequeue() {
                if latest.isDisposed {
                    continue
                }
                latest.invoke()
            }

当回到currentThreadScheduler时,取出当前queue,并取出其value,也就是scheduledItem,调用其invoke方法

func invoke() {
         self._disposable.setDisposable(self._action(self._state))
    }

执行R闭包,走到这一句时

if let action = action {
                action(state, self.schedule)
            }

在这里开始调用RecursiveScheduler保存的原始闭包,并传进去自己的schedule函数,进行迭代,然后来到ObserveOnSerialDispatchQueueSink的onCore方法里

override func onCore(_ event: Event) {
        _ = self.scheduler.schedule((self, event), action: self.cachedScheduleLambda!)
    }

调用self.scheduler.schedule,这里的scheduler,就是指定的scheduler,传进去一个元组( >,next(3) ),和一个lambda来到

public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
        return self.scheduleInternal(state, action: action)
    }

来到子类MainScheduler的scheduleInternal方法

override func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
        let previousNumberEnqueued = increment(self.numberEnqueued)

        if DispatchQueue.isMain && previousNumberEnqueued == 0 {
            let disposable = action(state)
            decrement(self.numberEnqueued)
            return disposable
        }

        let cancel = SingleAssignmentDisposable()
//抛开此例,一般是来到这里开始新开线程执行,
//MainScheduler是在DispatchQueue.main上,
//SerialDispatchQueueScheduler是通过DispatchQueueConfiguration在新建串行queue上开线程执行
        self._mainQueue.async {
            if !cancel.isDisposed {
                _ = action(state)
            }

            decrement(self.numberEnqueued)
        }

        return cancel
    }

开始执行ObserveOnSerialDispatchQueueSink里面的cachedScheduleLambda,传过去刚刚那个元组

self.cachedScheduleLambda = { pair in
            guard !cancel.isDisposed else { return Disposables.create() }

            pair.sink.observer.on(pair.event)

            if pair.event.isStopEvent {
                pair.sink.dispose()
            }

            return Disposables.create()
        }

pair.sink.observer.on(pair.event) on就执行了最开始subscribe里面的print方法
然后是一系列方法返回,直到

while let latest = queue.value.dequeue() {
                if latest.isDisposed {
                    continue
                }
                latest.invoke()
            }

再次执行原始闭包

待续

你可能感兴趣的:(observeOn)