美文网首页
框架学习1.1RxSwift-定时器

框架学习1.1RxSwift-定时器

作者: 数字d | 来源:发表于2019-07-24 17:21 被阅读0次

    1.常规步骤,RX的pod导入
    参看:https://www.jianshu.com/p/ba33981cf597
    2.创建UI序列

     let isRunning = Observable
                .merge([startBtn.rx.tap.map({return true}), stopBtn.rx.tap.map({return false})])
                .startWith(false)
                .share(replay: 1, scope: .whileConnected)
    
    let isNotRunning = isRunning
                .map({running -> Bool in
                    print(running)
                    return !running
                })
                .share(replay: 1, scope: .whileConnected)
    
    

    3.UI序列响应绑定

          isRunning.subscribe(onNext:{
                print($0)
            })
                .disposed(by: disposBag)
    
        isRunning
                .bind(to: stopBtn.rx.isEnabled)
                .disposed(by: disposBag)
            
            isNotRunning
                .bind(to: splitBtn.rx.isHidden)
                .disposed(by: disposBag)
            
            isNotRunning
                .bind(to: startBtn.rx.isEnabled)
                .disposed(by: disposBag)
    

    4.创建定时器序列

      timer = Observable<Int>
                .interval(0.1, scheduler: MainScheduler.instance)
                .withLatestFrom(isRunning, resultSelector: {_, running in running})
                .filter({runing in runing})
                .scan(0, accumulator: {(acc, _) in
                    return acc+1
                })
                .startWith(0)
                .share(replay: 1, scope: .whileConnected)
    

    5.定时器序列事件响应绑定

            timer
                .subscribe{ (mecs) in
                    print("\(mecs)00ms")
                }
                .disposed(by: disposBag)
            
            
            timer.map(stringFromTimeInterval)
                .bind(to: self.topLab.rx.text)
                .disposed(by: disposBag)
    
    

    6.其他序列的创建和绑定流程

            let lapsSequence = timer
                .sample(splitBtn.rx.tap)
                .map(stringFromTimeInterval)
                .scan([String](), accumulator: { lapTimes, newTime in
                    return lapTimes + [newTime]
                })
                .share(replay: 1, scope: .whileConnected)
            
            lapsSequence
                .bind(to: scView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in
                    cell.textLabel?.text = "\(row+1)) \(element)"
                }
                .disposed(by: disposBag)
    
    

    7.实现效果

    1.png

    代码地址:https://gitee.com/xgkp/Rx1point1.git

    相关文章

      网友评论

          本文标题:框架学习1.1RxSwift-定时器

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