RxSwift中timer不受runloop的影响可以正常计时,以下探索timer实现原理。
Timer
- swift创建timer
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
timer = Timer.init(timeInterval: 1, target: self, selector: #selector(timerFire), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: .default)
}
@objc func timerFire() {
print(NSDate())
}
/*
输出结果:
2019-08-04 10:27:38 +0000
2019-08-04 10:27:39 +0000
2019-08-04 10:27:40 +0000
2019-08-04 10:27:41 +0000
2019-08-04 10:27:42 +0000
……
*/
- 当页面有滚动事件时定时器会停止计时,滚动事件结束定时器继续计时。
- 把定时器加到Runloop的
.common
Mode中,滚动事件不影响定时器计时,但是在commonMode里执行会影响整个程序,且不容易处理
- Timer.scheduledTimer的写法
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerFire), userInfo: nil, repeats: true)
- Timer.scheduledTimer的写法在页面有滚动事件时定时器会停止计时,说明此方法加进了runloop的
.default
Mode里
DispatchSourceTimer
- swift创建gcdTimer
gcdTimer = DispatchSource.makeTimerSource()
gcdTimer?.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(1))
gcdTimer?.setEventHandler(handler: {
print("gcdTimer:\(NSDate())")
})
gcdTimer?.resume()
/*
输出结果:
gcdTimer:2019-08-04 11:18:13 +0000
gcdTimer:2019-08-04 11:18:14 +0000
gcdTimer:2019-08-04 11:18:15 +0000
gcdTimer:2019-08-04 11:18:16 +0000
gcdTimer:2019-08-04 11:18:17 +0000
……
*/
- gcdTimer,滚动事件不影响定时器计时,这种方式计时更准确有效
- gcdTimer操作
gcdTimer?.suspend() //挂起,gcdTimer挂起后一定要取消置空
gcdTimer?.cancel() //取消,先取消再置空
gcdTimer = nil //置空
CADisplayLink
- swift创建cadTimer
cadTimer = CADisplayLink(target: self, selector: #selector(timerFire))
cadTimer?.preferredFramesPerSecond = 1
cadTimer?.add(to: RunLoop.current, forMode: .default)
- cadTimer也是加入到runloop的
.default
Mode里,滚动事件时定时器会停止计时
RxSwift timer
- RxSwift创建timer
Observable<Int>.interval(1, scheduler: MainScheduler.instance).subscribe(onNext: { (num) in
print(num)
})
.disposed(by: disposeBag)
- RxSwift的timer计时不受滑动时间影响,底层是封装了GCD执行计时
- interval的实现
public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return Timer(
dueTime: period,
period: period,
scheduler: scheduler
)
}
-
Timer类的实现
Timer类继承于Producer,执行run方法,run方法里创建TimerSink
/*继承于Producer,执行run方法,Producer里的run方法由子类来实现*/
final private class Timer<Element: RxAbstractInteger>: Producer<Element> {
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 //间隔时间
}
//执行run方法
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
if self._period != nil {
//创建TimerSink,然后执行sink.run
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)
}
}
}
- TimerSink,init初始化,实现run方法
final private class TimerSink<Observer: ObserverType> : Sink<Observer> where Observer.Element : RxAbstractInteger {
typealias Parent = Timer<Observer.Element>
private let _parent: Parent
private let _lock = RecursiveLock()
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
//执行schedulePeriodic方法
return self._parent._scheduler.schedulePeriodic(0 as Observer.Element, 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方法,创建了GCD计时器并处理定时器回调
func schedulePeriodic<StateType>(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable {
let initial = DispatchTime.now() + startAfter
var timerState = state
// 创建GCD计时器
let timer = DispatchSource.makeTimerSource(queue: self.queue)
timer.schedule(deadline: initial, repeating: 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
}
- action是闭包的传值,往上找可以在TimerSink的run方法找到action的实现,action里执行self.forwardOn(.next(state))发送消息,也就是执行subscribe(onNext:)方法返回到闭包里执行打印
func run() -> Disposable {
return self._parent._scheduler.schedulePeriodic(0 as Observer.Element, startAfter: self._parent._dueTime, period: self._parent._period!) { state in //尾随闭包action实现
self._lock.lock(); defer { self._lock.unlock() }
self.forwardOn(.next(state))
return state &+ 1 //按位与操作,地址+1,改变状态
}
}
- timer序列停止计时
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//timer已经加入到disposeBag里,这里将disposeBag重新赋值即可销毁timer停止计时
disposeBag = DisposeBag()
}