The Map operator applies the transformation method you provide to each element of the source Observable and returns the Observable with the result of the transformation — the new Observable sequence.

Example:

let ob = Observable.of(1.2.3.4)
      
ob.map { (num) -> Int in
    return num + 2
}
.subscribe(onNext: { (num) in
    print("num: \(num)")
})
.disposed(by: disposeBag)
Copy the code
Num: 3 num: 4 num: 5 num: 6Copy the code

Map source code analysis

Click on the map function to access the source code here.

blog

Map
map

self.asObservable().composeMap(transform)
Copy the code

As analyzed in previous articles, asObservable() returns self and converts it into an Observable. Therefore, we should look for the source of the composeMap function

Observable
composeMap

_map

Producer
Map
source
transform

The above analysis is the process of calling the map function. We also know that the Map object inherits from the Producer object. Those of you who have seen RxSwift’s core logic analysis know that when an observable sequence subscribes, it calls the subclass’s run function. Let’s analyze the Map object’s run function.

    override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E= =ResultType {
        let sink = MapSink(transform: self._transform, observer: observer, cancel: cancel)
        let subscription = self._source.subscribe(sink)
        return (sink: sink, subscription: subscription)
    }
Copy the code

In the run function, the MapSink object is initialized and the transformation method and observer are stored in it. The specific analysis can be analogous to AnonymousObservableSink in RxSwift core logic analysis.

Then execute self._source.subscribe(sink) to subscribe to the original sequence!! Because the original signal must be sent by the source sequence, nothing else.

So eventually, you’re going to come to sink’s on function. So we focus on the analysis of MapSink’s on function.

let mappedElement = try self._transform(element)

The above is the transformation process of map function. If there are inadequacies, also ask friends to comment and correct.