03.RxSwift Timer的几种实现方式

本文详细介绍了五种常见的计时器实现方式,包括NStimer、DispatchSourceTimer、CADisplayLink、RxSwiftTimer等,探讨了它们的初始化、运行机制及应用场景,特别指出不同计时器对UI滚动响应的敏感度和准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

几种常见的timer的实现方式:

1.NStimer
  • init
//1.如果没有把timer添加到RunLoop的,调用timer.fire()只会执行一次,添加RunLoop以后 就不需要再调用timer.fire()
timer = Timer.init(timeInterval: 1, target: self, selector: #selector(timerFire), userInfo: nil, repeats: true)
//timer.fire()
//2.一般默认是default,但是当UI滚动的是timer会不执行,可设置为common
RunLoop.current.add(timer, forMode: .default)
  • scheduledTimer
//也是默认把timer添加到RunLoop的default里边的,当UI滚动的是timer也会不执行
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
    print(timer)
 })
  • 如果没有把timer添加到RunLoop的,调用timer.fire()只会执行一次,添加RunLoop以后 就不需要再调用timer.fire()
  • 一般默认是default,但是当UI滚动的是timer会不执行,可设置为common, 他的准确性依赖RunLoop的状态
2.DispatchSourceTimer
// 精确 - GCD 封装timer
// 封装了一套GCD PRODUCER 环境
//不受UI滚动的响应
//初始化
gcdTimer = DispatchSource.makeTimerSource()
gcdTimer?.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(1))
gcdTimer?.setEventHandler(handler: {
     print("hello GCD")
})
//默认是挂起的需要执行resume()
gcdTimer?.resume()
  • 装了一套GCD PRODUCER 环境
  • 不受UI滚动的响应,准确性比较高
3.CADisplayLink
cadTimer = CADisplayLink(target: self, selector: #selector(timerFire)) cadTimer?.preferredFramesPerSecond = 1
//也是需要加入runLoop,也是会受UI滚动影响
cadTimer?.add(to: RunLoop.current, forMode: .default)
  • CADisplayLink 不能被继承
  • 也是需要加入runLoop,也是会受UI滚动影响
4.RxSwift Timer
//不受UI滚动的响应, 底层是DispatchSourceTimer的封装
timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
timer.subscribe(onNext: { (num) in
            print(num)
        })
        .disposed(by: disposeBag)
  • 底层是DispatchSourceTimer的封装
5.实现方式总结
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值