iOS-swiftRXswiftRxSwift干货

RxSwift文档翻译4-- Transforming Oper

2017-06-01  本文已影响124人  小白猿

前言

Transforming Operators 将观察序列的Next事件元素做转换的操作

Transforming Operators

example("map") {
    let disposeBag = DisposeBag()
    Observable.of(1, 2, 3)
        .map { $0 * $0 }
        .subscribe(onNext: { print($0) })
        .disposed(by: disposeBag)
}
// 控制台打印的结果:
--- map example ---
1
4
9
example("flatMap and flatMapLatest") {
    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() }
        .subscribe(onNext: { print($0) })
        .disposed(by: disposeBag)
    
    👦🏻.score.value = 85
    
    player.value = 👧🏼
    
    👦🏻.score.value = 95 
    
    👧🏼.score.value = 100

// 控制台打印的结果:
--- flatMap and flatMapLatest example ---
80
85
90
95
100

如果将 flatMap修改为flatMapLatest,那么 player.value 设置为👧🏼的时候, 👦🏻.score.value 就不会被相应,类似于switchLatest,只会相应最近的元素,此时打印结果为

// 控制台打印的结果:
--- flatMap and flatMapLatest example ---
80
85
90
100
    Observable.of(10, 100, 1000)
        .scan(1) { aggregateValue, newValue in
            aggregateValue + newValue
        }
        .subscribe(onNext: { print($0) })
        .disposed(by: disposeBag)
}
// 控制台打印的结果:
--- scan example ---
11
111
1111

scan后边的值就是种子,aggregateValue是原始值,newValue是新值,aggregateValue + newValue是具体的操作,过程就是 1 + 10,(1+10)+100, ((1+10)+100) + 1000

下一节:RxSwift文档翻译5 -- Filtering and Conditional Operators

上一篇下一篇

猜你喜欢

热点阅读