简介
git地址: https://github.com/ReactiveX/RxSwift 参考资料:http://t.swift.gg/d/2-rxswift ReactiveX是通过可观察的流实现异步编程的一种API,它结合了观察者模式、迭代器模式和函数式编程的精华,RxSwift 是 ReactiveX 编程思想的一种实现。复制代码
map
map可以通过你指定的操作对序列发送的数据进行转换.复制代码
let bag = DisposeBag()let originalSequence = Observable.of(1, 2, 3) originalSequence .map { $0 * 2 } .subscribe { print($0) } .addDisposableTo(bag)///带indexoriginalSequence .mapWithIndex { number, index in number * index } .subscribe { print($0) } .addDisposableTo(disposeBag) 复制代码
flatMap
将一个序列发送的数据转换成另一个新的序列,生成的新序列会按照先后顺序平压到一个序列之中.
eg1:let sequenceInt = Observable.of(1, 2, 3)let sequenceString = Observable.of("A", "B", "C", "D", "E", "F", "--")sequenceInt .flatMap { (x: Int) -> Observablein print("from sequenceInt \(x)") return sequenceString } .subscribe { print($0) } .addDisposableTo(disposeBag)///输出: from sequenceInt 1Next(A)Next(B)Next(C)Next(D)Next(E)Next(F)Next(--)from sequenceInt 2Next(A)Next(B)eg2:let disposeBag = DisposeBag()struct Player { var score: Variable //里面是一个Variable}let ?? = Player(score: Variable(80)) let ?? = Player(score: Variable(90))let ? = Player(score: Variable(550))let player = Variable(??) //将player转为Variableplayer.asObservable() //拆箱转成可被监听的sequence .flatMap { $0.score.asObservable() } // flatMap有一次拆包动作,$0本来应该是一个BehaviorSubject类型,但是直接访问了score。所以猜想flatMap对behaviorSubject进行了onNext拆包取数据 .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag)??.score.value = 85player.value = ?? //更换了value,相当于又添加了一个sequence,两个sequence都可以接收??.score.value = 95??.score.value = 222player.value = ???.score.value = 100///输出:80859095222550100复制代码
flatMapLatest
flatMapLatest 与 flatMap的区别在于,flatMapLatest会抛弃旧值. 例如上面的eg2,更改为flatMapLatest后,会输出:
808590550复制代码
scan
scan会要求有一个初始值,通过闭包对前一个元素和当前元素做处理,并将处理的元素放在一个序列中返回.
let disposeBag = DisposeBag() Observable.of(10, 100, 1000) .scan(2) { aggregateValue, newValue in aggregateValue + newValue } .subscribe(onNext: { print($0) }) .disposed(by: disposeBag)输出:121121112复制代码
reduce
跟scan类似,不同的是reduce只会在序列结束时发送一个最终值.
buffer和window
buffer在特定的线程,定期定量收集序列发射的值,然后发射这些的值的集合。
sequenceToSum .buffer(timeSpan: 5, count: 2, scheduler: MainScheduler.instance) .subscribe { print($0) }.addDisposableTo(disposeBag)输出:Next([0, 1])Next([2, 3])Next([4, 5])Next([])Completed出现Next([])是因为 buffer 并不知道上次的发射的值是最后一个值,只有当收到 Completed 才知道序列已经结束,所以没有缓冲到任何值,只好发射 [] 了。复制代码
window与buffer的不同在于,window返回的是序列
sequenceToSum .window(timeSpan: 5, count: 2, scheduler: MainScheduler.instance) .subscribe { print($0) }.addDisposableTo(disposeBag)输出:Next(RxSwift.AddRef)Next(RxSwift.AddRef )Next(RxSwift.AddRef )Next(RxSwift.AddRef )Completed复制代码
注:
如有侵权,请告之删除.