The starting address: www.ljcoder.com/16080130499…

RxSwift operator

Operators can help you create new sequences, or combine existing sequences to generate a new sequence. For example, filter and map conversion, see the documentation operator-operator.

Operators such as filter and map are higher-order functions that take one or more functions as input and output a function. Let’s take MAP as an example for analysis.

Analysis of MAP Principle

Let’s start with the simplest map usage code

let ob = Observable.of(1.2.3.4)
ob.map { (number) -> Int in
        return number+2
    }
    .subscribe{
        print("\ [$0)")
    }
    .disposed(by: disposeBag)
Copy the code

To viewmapFunction, as you can see in the comments section, is implemented in the map file

// Map.swift

extension ObservableType {
    public func map<Result> (_ transform: @escaping (Element) throws -> Result)
        -> Observable<Result> {
        return Map(source: self.asObservable(), transform: transform)
    }
}
Copy the code

In RxSwift core logic analysis, AnonymousObservable is also a subclass of Producer. There should be some similarities between them. Let’s analyze the differences.

final private class Map<SourceType.ResultType> :Producer<ResultType> {
    typealias Transform = (SourceType) throws -> ResultType

    private let source: Observable<SourceType>

    private let transform: Transform

    init(source: Observable<SourceType>, transform: @escaping Transform) {
        self.source = source
        self.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)
    }
}
Copy the code
  • Much moresourceProperty to store the original queue,transformStore the transformation logic, which is.mapClosure in the backreturn number+2.
  • sinkAlso byAnonymousObservableSinkTurned out to beMapSink.
  • subscriptionissourcethesubscribeThe return value.

As we already know from RxSwift- core logic analysis, MapSink’s on(_:) method is finally called.

final private class MapSink<SourceType.Observer: ObserverType> :Sink<Observer>, ObserverType {
    typealias Transform = (SourceType) throws -> ResultType

    typealias ResultType = Observer.Element 
    typealias Element = SourceType

    private let transform: Transform

    init(transform: @escaping Transform.observer: Observer.cancel: Cancelable) {
        self.transform = transform
        super.init(observer: observer, cancel: cancel)
    }

    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()
        }
    }
}

Copy the code

Next, element is the element of the source sequence (1,2,3,4), transform is called, number+2, and the transformed element is sent, and the map is complete.

// If the sequence element is 1, the sequence element is 3 after number+2
let mappedElement = try self.transform(element)
// If you send 3, the subscribed element becomes 3
self.forwardOn(.next(mappedElement))
Copy the code

conclusion

  • The subscription and response logic of higher-order functions is the same as that of ordinary sequences.
  • Different higher-order functions have different logicProducerSubclasses and differentSinkSubclasses are processed to ensure the flexibility and extensibility of the sequence.