<conversion operator> of RxSwift official use example

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 Observablesequence and returns a new Observablesequence of transformed elements

image.png

let disposeBag = DisposeBag()
Observable.of(1, 2, 3)
    .map { $0 * $0 }
    .subscribe(onNext: { print($0) })
    .disposed(by: disposeBag)

Print

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)
}

Print

80
85
90
95
100

scan

Start with an initial seed value, then apply an accumulator closure to each element emitted by the Observablesequence and return each intermediate result as an element Observablesequence

image.png

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

Print

11
111
1111

Guess you like

Origin juejin.im/post/7117938639002140680