要学习RxSwift-Timer
的实现逻辑,可以先看RxSwift核心逻辑分析。理解RxSwift核心逻辑后,在来学习RxSwift其他类的实现逻辑会事半功倍。
分析RxSwift
的Timer
之前,我们先看一下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.interval(1, scheduler: MainScheduler.instance)
timer.subscribe(onNext: { (num) in
//block_1
print(num)
})
.disposed(by: disposeBag)
我们都知道传统的Timer
和CADisplayLink
一样,在runloop mode
为.default
时,UI操作会影响Timer。在runloop mode
为.common
时,Timer
不收UI操作影响。gcdTimer
不受UI操作影响,计时更精准。
RxSwift Timer
下创建的Timer经测试也不受UI操作影响。那它是由上面哪一种方法封装实现的,或者说是另外新的实现方式?带着问题,我们进入RxSwift-Timer源码分析
。
RxSwift Timer源码分析
一、从Timer
的创建入手:
timer = Observable.inter val(1, scheduler: MainScheduler.instance)
进入Timer.swift
的interval
源码, ObservableType
的扩方法。
public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType)
-> Observable {
return Timer(
dueTime: period,
period: period,
scheduler: scheduler
)
}
interval
方法源码的调用传入了2个参数:
period
是TimeInterval类型,表示执行每一次的时间周期
scheduler
是调度者,这里暂不展开说明。
源码中返回Timer
对象。进入Timer
类的源码:
final private class Timer: Producer {
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(_ 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
等外界传入的参数。
二、接下来分析Timer
的subscribe
的调用:
timer.subscribe(onNext: { (num) in
print(num)
})
subscribe
的逻辑和RxSwift核心逻辑分析的逻辑基本一致,不同的是Timer
的run
方法调用的Sink.run
不再是AnonymousObservableSink
,而是 TimerSink
。这里也是RxSwift
设计的牛逼之处,不同的业务模块由不同的Sink
处理。TimerSink
中保存了Timer
对象至_parent
属性。
override func run(_ 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 {
// .......
}
}
进入TimerSink
的run
方法:
final private class TimerSink : Sink where O.E : RxAbstractInteger {
typealias Parent = Timer
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(_ 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,足以说明RxSwift
的Timer
使用的是GCD
的Timer
其实不难理解,GCD
的Timer
不受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
那么RxSwift
的Timer
该如何停止呢?
Timer
是一个无限序列,只要序列完成
, 错误
, 销毁
,序列就会结束,timer停止。
disposeBag = DisposeBag()
垃圾袋销毁,垃圾袋中的Timer也会销毁。