美文网首页
RXSwift中的timer浅析(一)

RXSwift中的timer浅析(一)

作者: 越来越胖了 | 来源:发表于2019-07-21 16:01 被阅读0次

OC创建一个timer很简单,直接使用NSTimer,然后加入到runloop就可以实现了:

       NSTimer *timer  = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

RXSwift中创建timer也很简单:

var timer: Observable<Int>!
timer = Observable<Int>.interval(5, scheduler: MainScheduler.instance)//放在主线程执行 MainScheduler.instance
        timer.subscribe(onNext: { (num) in
            print(num)
        })
        .disposed(by: disposeBag)

但是RX中的timer,其实和OC中的timer完全不一样,rx是创建了一个无穷的可观察序列,让观察者去监听这个可观察序列,如上,是每5秒,可观察序列发送一个响应,观察者订阅后接收到对应的event事件,从而实现了一个类似于timer的功能。下篇对RXSwift的核心逻辑进行一个初步的剖析,了解后应该可以更好的理解这个timer的实现。

相关文章

网友评论

      本文标题:RXSwift中的timer浅析(一)

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