前言

本篇文章将要学习RxSwift中四种转换操作符:

  • map
  • flatMap
  • flatMapLatest
  • scan

map

通过使用一个闭包函数将原来的Observable序列转换为一个新的Observable序列。
RxSwift 系列(四)-LMLPHP

let disposeBag = DisposeBag()

    Observable.of(1,2,3).map({return 10 * $0}).subscribe({print($0)}).disposed(by: disposeBag)

打印结果:

next(10)
next(20)
next(30)
completed

flatMap

将一个Observable序列转换为另一个Observable序列,并且合并两个Observable序列。会按时间顺序接收两个序列发出的元素。

let disposeBag = DisposeBag()

struct Player {
var score:Variable<Int>
} let man = Player(score: Variable(80))
let women = Player(score: Variable(90)) let player = Variable(man)
player.asObservable().flatMap({$0.score.asObservable()}).subscribe(onNext: {print($0)}).disposed(by: disposeBag) man.score.value = 85
player.value = women
man.score.value = 95
women.score.value = 100

打印结果:

80
85
90
95
100

flatMapLatest

flatMapLatestflatMap一样,也是将一个序列转换为另一个序列,flatMapLatest只会从最近的序列中发出事件。

  • 疑问:感觉和switchLatest没什么区别啊。(有哪位大佬帮忙解答一下么
let disposeBag = DisposeBag()

struct Player {
var score:Variable<Int>
} let man = Player(score: Variable(80))
let women = Player(score: Variable(90)) let player = Variable(man)
player.asObservable().flatMapLatest({$0.score.asObservable()}).subscribe(onNext: {print($0)}).disposed(by: disposeBag) man.score.value = 85
player.value = women
man.score.value = 95
women.score.value = 100

打印结果:

80
85
90
100

scan

scan就是提供一个初始化值,然后使用计算闭包不断将前一个元素和后一个元素进行处理,并将处理结果作为单个元素的Observable序列返回。

let disposeBag = DisposeBag()

Observable.of(10, 100, 1000)
.scan(2) { aggregateValue, newValue in
aggregateValue + newValue
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)

打印结果:

12
112
1112

致谢

如果发现有错误的地方,欢迎评论,感谢!

05-14 14:59