RxSwift 操作符 (filter & map & reduce)

filter & map & reduce

ReactiveX:
filter: emit only those items from an Observable that pass a predicate test
map: transform the items emitted by an Observable by applying a function to each item
reduce: apply a function to each item emitted by an Observable, sequentially, and emit the final value

filter 过滤
map 转换
reduce 将一个函数作用于它,并得到一个最终值
效果和swift的filter,map,reduce一样。

Observable.from([1, 2, 3, 4, 5])
    .filter { $0 > 3 }
    .subscribe(onNext: { element in
        print("element:", element)
    })
    .disposed(by: bag)
print("-------")
Observable.from([1, 2, 3, 4, 5])
    .map { $0 + 10 }
    .subscribe(onNext: { element in
        print("element:", element)
    })
    .disposed(by: bag)
print("-------")
Observable.from([1, 2, 3, 4, 5])
    .reduce(0, accumulator: { $0 + $1 })
    .subscribe(onNext: { element in
        print("element:", element)
    })
    .disposed(by: bag)

输出:
element: 4
element: 5
*---------*
element: 11
element: 12
element: 13
element: 14
element: 15
*---------*
element: 15

你可能感兴趣的:(RxSwift 操作符 (filter & map & reduce))