Enumerated
Enumerates the elements of an observable sequence.
1
2
3
4
public func enumerated()
-> Observable<(index: Int, element: Element)> {
return Enumerated(source: self.asObservable())
}
final private class EnumeratedSink<Element, Observer: ObserverType>: Sink, ObserverType where Observer.Element == (index: Int, element: Element)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var index = 0
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
do {
// too easy to unserstand
let nextIndex = try incrementChecked(&self.index)
let next = (index: nextIndex, element: value)
self.forwardOn(.next(next))
}
catch let e {
self.forwardOn(.error(e))
self.dispose()
}
case .completed:
self.forwardOn(.completed)
self.dispose()
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
}
}
final private class Enumerated: Producer<(index: Int, element: Element)>
1
2
3
4
5
6
private let _source: Observable<Element>
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == (index: Int, element: Element) {
let sink = EnumeratedSink<Element, Observer>(observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}