(*useful)标记:目前觉得有用的函数
//FIXME 标记:待补充
Transform:(转换Next event)
转换由可观察序列发出的下一个事件元素的操作。
map:(*useful)将elements emitted 的事件转换后发出一个新的Observable sequence
转换elemet
let disposeBag = DisposeBag()
Observable.of(1, 2, 3)
.map { $0 * $0 }
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
打印:
--- map example ---
1
4
9
flatMap and flatMapLatest:
flatMapLatest实际上是Map和switchLatest的组合。
let disposeBag = DisposeBag()
struct Player {
var score: Variable<Int>
}
let 👦🏻 = Player(score: Variable(80))
let 👧🏼 = Player(score: Variable(90))
let player = Variable(👦🏻)
player.asObservable()
.flatMap { $0.score.asObservable() } // Change flatMap to flatMapLatest and observe change in printed output
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
👦🏻.score.value = 85
player.value = 👧🏼
👦🏻.score.value = 95 // Will be printed when using flatMap, but will not be printed when using flatMapLatest
👧🏼.score.value = 100
打印: //FIXME :flatMap理解不到位
80
85
90
95 //Will be printed when using flatMap, but will not be printed when using flatMapLatest
100
scan:累加器
let disposeBag = DisposeBag()
Observable.of(10, 100, 1000)
.scan(2) { aggregateValue, newValue in
aggregateValue + newValue
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
打印:
--- scan example ---
12
112
1112