The examples in this article are mainly from the official example code, which can be downloaded from here . The example code has been slightly modified. The pictures are from reactivex.io/
The main function of this article is to view the example code and view the effect of the corresponding example code, without running the project
map
applies a transformation closure to the elements emitted by the Observable
sequence and returns a new Observable
sequence of transformed elements
let disposeBag = DisposeBag()
Observable.of(1, 2, 3)
.map { $0 * $0 }
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
1
4
9
flatMap and flatMapLatest
Personal understanding: flatMap = map + merge ; flatMapLatest = map + switchLatest
let disposeBag = DisposeBag()
struct Player {
init(score: Int) {
self.score = BehaviorSubject(value: score)
}
let score: BehaviorSubject<Int>
}
let A = Player(score: 80)
let B = Player(score: 90)
let player = BehaviorSubject(value: A)
player.asObservable()
.flatMap { $0.score.asObservable() } // Change flatMap to flatMapLatest and observe change in printed output
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
A.score.onNext(85)
player.onNext(B)
A.score.onNext(95) // Will be printed when using flatMap, but will not be printed when using flatMapLatest
B.score.onNext(100)
}
80
85
90
95
100
scan
Start with an initial seed value, then apply an accumulator closure to each element emitted by the Observable
sequence and return each intermediate result as an element Observable
sequence
let disposeBag = DisposeBag()
Observable.of(10, 100, 1000)
.scan(1) { aggregateValue, newValue in
aggregateValue + newValue
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
11
111
1111