03.RxSwift Timer的幾種實(shí)現(xiàn)方式

幾種常見(jiàn)的timer的實(shí)現(xiàn)方式:

1.NStimer
  • init
//1.如果沒(méi)有把timer添加到RunLoop的,調(diào)用timer.fire()只會(huì)執(zhí)行一次,添加RunLoop以后 就不需要再調(diào)用timer.fire()
timer = Timer.init(timeInterval: 1, target: self, selector: #selector(timerFire), userInfo: nil, repeats: true)
//timer.fire()
//2.一般默認(rèn)是default,但是當(dāng)UI滾動(dòng)的是timer會(huì)不執(zhí)行,可設(shè)置為common
RunLoop.current.add(timer, forMode: .default)

  • scheduledTimer
//也是默認(rèn)把timer添加到RunLoop的default里邊的,當(dāng)UI滾動(dòng)的是timer也會(huì)不執(zhí)行
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
    print(timer)
 })
  • 如果沒(méi)有把timer添加到RunLoop的,調(diào)用timer.fire()只會(huì)執(zhí)行一次,添加RunLoop以后 就不需要再調(diào)用timer.fire()
  • 一般默認(rèn)是default,但是當(dāng)UI滾動(dòng)的是timer會(huì)不執(zhí)行,可設(shè)置為common, 他的準(zhǔn)確性依賴RunLoop的狀態(tài)
2.DispatchSourceTimer
// 精確 - GCD 封裝timer
// 封裝了一套GCD PRODUCER 環(huán)境
//不受UI滾動(dòng)的響應(yīng)
//初始化
gcdTimer = DispatchSource.makeTimerSource()
gcdTimer?.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(1))
gcdTimer?.setEventHandler(handler: {
     print("hello GCD")
})
//默認(rèn)是掛起的需要執(zhí)行resume()
gcdTimer?.resume()

  • 裝了一套GCD PRODUCER 環(huán)境
  • 不受UI滾動(dòng)的響應(yīng),準(zhǔn)確性比較高
3.CADisplayLink
cadTimer = CADisplayLink(target: self, selector: #selector(timerFire)) cadTimer?.preferredFramesPerSecond = 1
//也是需要加入runLoop,也是會(huì)受UI滾動(dòng)影響
cadTimer?.add(to: RunLoop.current, forMode: .default)
  • CADisplayLink 不能被繼承
  • 也是需要加入runLoop,也是會(huì)受UI滾動(dòng)影響
4.RxSwift Timer
//不受UI滾動(dòng)的響應(yīng), 底層是DispatchSourceTimer的封裝
timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
timer.subscribe(onNext: { (num) in
            print(num)
        })
        .disposed(by: disposeBag)
  • 底層是DispatchSourceTimer的封裝
5.實(shí)現(xiàn)方式總結(jié)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容