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.实现效果