Home Rxswift Operator Map
Post
Cancel

Rxswift Operator Map

Map

Projects each element of an observable sequence into a new form.

1
2
3
4
public func map<Result>(_ transform: @escaping (Element) throws -> Result)
    -> Observable<Result> {
    return Map(source: self.asObservable(), transform: transform)
}

final private class MapSink<SourceType, Observer: ObserverType>: Sink, ObserverType

中间订阅层,用于中间处理,产生最终结果,输出给最终Observer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
typealias ResultType = Observer.Element 
typealias Transform = (SourceType) throws -> ResultType

private let _transform: Transform

func on(_ event: Event<SourceType>) {
    switch event {
    case .next(let element):
        do {
            let mappedElement = try self._transform(element)
            self.forwardOn(.next(mappedElement))
        }
        catch let e {
            self.forwardOn(.error(e))
            self.dispose()
        }
    case .error(let error):
        self.forwardOn(.error(error))
        self.dispose()
    case .completed:
        self.forwardOn(.completed)
        self.dispose()
    }
}

final private class Map<SourceType, ResultType>: Producer

1
2
3
4
5
6
7
8
9
10
typealias Transform = (SourceType) throws -> ResultType

private let _source: Observable<SourceType>
private let _transform: Transform

override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType {
    let sink = MapSink(transform: self._transform, 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.