美文网首页
RxSwift-Timer源码分析

RxSwift-Timer源码分析

作者: king_jensen | 来源:发表于2019-07-30 22:46 被阅读0次

    要学习RxSwift-Timer的实现逻辑,可以先看RxSwift核心逻辑分析。理解RxSwift核心逻辑后,在来学习RxSwift其他类的实现逻辑会事半功倍。

    分析RxSwiftTimer之前,我们先看一下Timer的创建的几种方式。

    Timer的创建

    方法一:传统Timer

       timer = Timer.init(timeInterval: 1, target: self, selector: #selector(timerFire), userInfo: nil, repeats: true)
                    RunLoop.current.add(timer, forMode: .default)
    

    方法二:GCD Timer

            gcdTimer = DispatchSource.makeTimerSource()
            gcdTimer?.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(1))
            gcdTimer?.setEventHandler(handler: {
                print("hello GCD")
            })
            gcdTimer?.resume()
    
    

    方法三:CADisplayLink

          cadTimer = CADisplayLink(target: self, selector: #selector(timerFire))
          cadTimer?.preferredFramesPerSecond = 1
          cadTimer?.add(to: RunLoop.current, forMode: .default)
           cadTimer?.isPaused = true
    

    方法四:RxSwift Timer

      timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
            timer.subscribe(onNext: { (num) in
                //block_1
                print(num)
            })
                .disposed(by: disposeBag)
    

    我们都知道传统的TimerCADisplayLink一样,在runloop mode.default时,UI操作会影响Timer。在runloop mode.common时,Timer不收UI操作影响。gcdTimer不受UI操作影响,计时更精准。
    RxSwift Timer下创建的Timer经测试也不受UI操作影响。那它是由上面哪一种方法封装实现的,或者说是另外新的实现方式?带着问题,我们进入RxSwift-Timer源码分析

    RxSwift Timer源码分析

    一、从Timer的创建入手:

    timer = Observable<Int>.inter val(1, scheduler: MainScheduler.instance)
    

    进入Timer.swiftinterval源码, ObservableType的扩方法。

     public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType)
            -> Observable<E> {
            return Timer(
                dueTime: period,
                period: period,
                scheduler: scheduler
            )
        }
    

    interval方法源码的调用传入了2个参数:
    period是TimeInterval类型,表示执行每一次的时间周期
    scheduler是调度者,这里暂不展开说明。

    源码中返回Timer对象。进入Timer类的源码:

    final private class Timer<E: RxAbstractInteger>: Producer<E> {
        fileprivate let _scheduler: SchedulerType
        fileprivate let _dueTime: RxTimeInterval
        fileprivate let _period: RxTimeInterval?
    
        init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) {
            self._scheduler = scheduler
            self._dueTime = dueTime
            self._period = period
        }
    
        override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
            if self._period != nil {
                let sink = TimerSink(parent: self, observer: observer, cancel: cancel)
                let subscription = sink.run()
                return (sink: sink, subscription: subscription)
            }
            else {
                let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel)
                let subscription = sink.run()
                return (sink: sink, subscription: subscription)
            }
        }
    }
    

    Timer初始化中保存_scheduler,_dueTime,_period

    总结:
    1.创建Timer对象,并返回
    2.Timer继承自Producer,拥有subscribe方法
    3.初始化方法中保存了_scheduler,_dueTime,_period等外界传入的参数。

    二、接下来分析Timersubscribe的调用:

     timer.subscribe(onNext: { (num) in
                print(num)
            })
    

    subscribe的逻辑和RxSwift核心逻辑分析的逻辑基本一致,不同的是Timerrun方法调用的Sink.run不再是AnonymousObservableSink,而是 TimerSink。这里也是RxSwift设计的牛逼之处,不同的业务模块由不同的Sink处理。TimerSink中保存了Timer对象至_parent属性。

    override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
            if self._period != nil {
                let sink = TimerSink(parent: self, observer: observer, cancel: cancel)
                let subscription = sink.run()
                return (sink: sink, subscription: subscription)
            }
            else {
              //  .......
            }
        }
    

    进入TimerSinkrun方法:

    final private class TimerSink<O: ObserverType> : Sink<O> where O.E : RxAbstractInteger  {
        typealias Parent = Timer<O.E>
    
        private let _parent: Parent
        private let _lock = RecursiveLock()
    
        init(parent: Parent, observer: O, cancel: Cancelable) {
            self._parent = parent
            super.init(observer: observer, cancel: cancel)
        }
    
        func run() -> Disposable {
            return self._parent._scheduler.schedulePeriodic(0 as O.E, startAfter: self._parent._dueTime, period: self._parent._period!) { state in
                self._lock.lock(); defer { self._lock.unlock() }
                self.forwardOn(.next(state))
                return state &+ 1
            }
        }
    }
    

    继续往下找,可以找到schedulePeriodic方法:

        func schedulePeriodic<StateType>(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable {
            let initial = DispatchTime.now() + dispatchInterval(startAfter)
    
            var timerState = state
    
            let timer = DispatchSource.makeTimerSource(queue: self.queue)
            timer.schedule(deadline: initial, repeating: dispatchInterval(period), leeway: self.leeway)
            
            // TODO:
            // This looks horrible, and yes, it is.
            // It looks like Apple has made a conceputal change here, and I'm unsure why.
            // Need more info on this.
            // It looks like just setting timer to fire and not holding a reference to it
            // until deadline causes timer cancellation.
            var timerReference: DispatchSourceTimer? = timer
            let cancelTimer = Disposables.create {
                timerReference?.cancel()
                timerReference = nil
            }
    
            timer.setEventHandler(handler: {
                if cancelTimer.isDisposed {
                    return
                }
                timerState = action(timerState)
            })
            timer.resume()
            
            return cancelTimer
        }
    

    代码中使用DispatchSource.makeTimerSource创建的Timer,足以说明RxSwiftTimer使用的是GCDTimer
    其实不难理解,GCDTimer不受runloop影响,并且比较计算精准,是用来封装Timer最好的选择。并且 RxSwift很多地方都应用了线程,对于线程RxSwift肯定不会放置不管,因此RxSwift封装了一套属于自己的GCD

         timer.setEventHandler(handler: {
                if cancelTimer.isDisposed {
                    return
                }
                timerState = action(timerState)
            })
    

    gcd Timer会不断执行handler代码块.代码块中执行timerState = action(timerState),
    那么action是什么?

    func run() -> Disposable {
            return self._parent._scheduler.schedulePeriodic(0 as O.E, startAfter: self._parent._dueTime, period: self._parent._period!) { state in
                self._lock.lock(); defer { self._lock.unlock() }
                self.forwardOn(.next(state))
                return state &+ 1
            }
        }
    

    action就是TimerSink.run方法中,调用self._parent._scheduler.schedulePeriodic带入的逃逸闭包block_1.

    self._lock.lock(); defer { self._lock.unlock() }
                self.forwardOn(.next(state))
                return state &+ 1
    

    闭包中,调用self.forwardOn(.next(state)),由RxSwift核心逻辑分析中,我们知道它最终会调用到observer.on方法,然后执行到外界订阅时传入的闭包block_1
    state &+ 1是位操作,每执行一次会+1

    那么RxSwiftTimer该如何停止呢?
    Timer是一个无限序列,只要序列完成, 错误 , 销毁,序列就会结束,timer停止。
    disposeBag = DisposeBag() 垃圾袋销毁,垃圾袋中的Timer也会销毁。

    相关文章

      网友评论

          本文标题:RxSwift-Timer源码分析

          本文链接:https://www.haomeiwen.com/subject/wpdnrctx.html