Home Rxswift Operator Filter
Post
Cancel

Rxswift Operator Filter

Filter

Filters the elements of an observable sequence based on a predicate.

1
2
3
4
public func filter(_ predicate: @escaping (Element) throws -> Bool)
    -> Observable<Element> {
    return Filter(source: self.asObservable(), predicate: predicate)
}

final private class FilterSink<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
typealias Predicate = (Element) throws -> Bool
private let _predicate: Predicate

func on(_ event: Event<Element>) {
    switch event {
    case .next(let value):
        do {
            let satisfies = try self._predicate(value)
          // too easy to understand
            if satisfies {
                self.forwardOn(.next(value))
            }
        }
        catch let e {
            self.forwardOn(.error(e))
            self.dispose()
        }
    case .completed, .error:
        self.forwardOn(event)
        self.dispose()
    }
}

final private class Filter: Producer

1
2
3
4
5
6
7
8
9
10
typealias Predicate = (Element) throws -> Bool

private let _source: Observable<Element>
private let _predicate: Predicate

override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
    let sink = FilterSink(predicate: self._predicate, observer: observer, cancel: cancel)
    let subscription = self._source.subscribe(sink)
    return (sink: sink, subscription: subscription)
}
This post is licensed under CC BY 4.0 by the author.