iOS-swiftRXswiftRxSwift干货

RxSwift文档翻译6 -- Mathematical and

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

前言

本章中主要介绍数学和一些综合运算符,操作是作用于整个观察序列的元素

Mathematical and Aggregate Operators

example("toArray") {
      let disposeBag = DisposeBag()
      Observable.range(start: 1, count: 10)
                .toArray()
                .subscribe { print($0) }
                .disposed(by: disposeBag)
        }

// 控制台打印的结果:
--- toArray example ---
next([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
completed
example("reduce") {
    let disposeBag = DisposeBag()
    
    Observable.of(10, 100, 1000)
        .reduce(1, accumulator: +)
        .subscribe(onNext: { print($0) })
        .disposed(by: disposeBag)
}

// 控制台打印的结果:
--- reduce example ---
1111

本文作者注:我所理解的结束,应该是序列发出Complete事件或者Error事件,并且在官方实例中子序列用的是BehaviorSubject,仅发出最近的元素,所以在比如A序列在前,B序列在后,B发出b1, b2两个元素,然后A Complete,由于b2是最近的元素,所以在链接的时候b1就会被忽略了*

example("concat") {
    let disposeBag = DisposeBag()
    
    let subject1 = BehaviorSubject(value: "🍎")
    let subject2 = BehaviorSubject(value: "🐶")
    
    let variable = Variable(subject1)
    
    variable.asObservable()
        .concat()
        .subscribe { print($0) }
        .disposed(by: disposeBag)
    
    subject1.onNext("🍐")
    subject1.onNext("🍊")
    
    variable.value = subject2
    
    subject2.onNext("I would be ignored")
    subject2.onNext("🐱")
    
    subject1.onCompleted()
    
    subject2.onNext("🐭")
}

// 控制台打印的结果:
--- concat example ---
next(🍎)
next(🍐)
next(🍊)
next(🐱)
next(🐭)

下一篇:RxSwift文档翻译7 - Connectable Operators

上一篇下一篇

猜你喜欢

热点阅读