ElementAt
Returns a sequence emitting only element n emitted by an Observable
1
2
3
4
public func elementAt(_ index: Int)
-> Observable<Element> {
return ElementAt(source: self.asObservable(), index: index, throwOnEmpty: true)
}
final private class ElementAtSink<Observer: ObserverType>: Sink, ObserverType
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
42
typealias SourceType = Observer.Element
typealias Parent = ElementAt<SourceType>
let _parent: Parent
var _i: Int
func on(_ event: Event<SourceType>) {
switch event {
case .next:
if self._i == 0 {
// until i == 0, got the answer
self.forwardOn(event)
// complete and dispose
self.forwardOn(.completed)
self.dispose()
}
do {
// decrement
_ = try decrementChecked(&self._i)
} catch let e {
self.forwardOn(.error(e))
self.dispose()
return
}
case .error(let e):
self.forwardOn(.error(e))
self.dispose()
case .completed:
// send complet will generator an error
// 需要注意的是,尽管如此,error有默认的处理方式,参考,在subscribe时,AnonymousObserver中的实现
if self._parent._throwOnEmpty {
self.forwardOn(.error(RxError.argumentOutOfRange))
} else {
self.forwardOn(.completed)
}
self.dispose()
}
}
final private class ElementAt: Producer
1
2
3
4
5
6
7
8
9
let _source: Observable<SourceType>
let _throwOnEmpty: Bool
let _index: Int
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceType {
let sink = ElementAtSink(parent: self, observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}