Reduce
Applies an accumulator
function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed
value is used as the initial accumulator value.
注意对比Scan
1
2
3
4
5
6
7
8
9
10
| public func reduce<A, Result>(_ seed: A, accumulator: @escaping (A, Element) throws -> A, mapResult: @escaping (A) throws -> Result)
-> Observable<Result> {
return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: mapResult)
}
public func reduce<A>(_ seed: A, accumulator: @escaping (A, Element) throws -> A)
-> Observable<A> {
return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 })
}
|
final private class Reduce<SourceType, AccumulateType, ResultType>: Producer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType
typealias ResultSelectorType = (AccumulateType) throws -> ResultType
private let _source: Observable<SourceType>
fileprivate let _seed: AccumulateType
fileprivate let _accumulator: AccumulatorType
fileprivate let _mapResult: ResultSelectorType
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType {
let sink = ReduceSink(parent: self, observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(let value):
do {
// too easy to understand
self._accumulation = try self._parent._accumulator(self._accumulation, value)
}
catch let e {
self.forwardOn(.error(e))
self.dispose()
}
case .error(let e):
self.forwardOn(.error(e))
self.dispose()
case .completed:
do {
let result = try self._parent._mapResult(self._accumulation)
self.forwardOn(.next(result))
self.forwardOn(.completed)
self.dispose()
}
catch let e {
self.forwardOn(.error(e))
self.dispose()
}
}
}
|
final private class ReduceSink<SourceType, AccumulateType, Observer: ObserverType>: Sink, ObserverType
1
2
3
4
| typealias ResultType = Observer.Element
typealias Parent = Reduce<SourceType, AccumulateType, ResultType>
private let _parent: Parent
private var _accumulation: AccumulateType
|