do运算

do运算符功能描述如下:


do运算_第1张图片
do运算符概念
extension ObservableType {
    /**
    Invokes an action for each event in the 
    observable sequence, and propagates all observer 
    messages through the result sequence.
    */
    public func doOn(eventHandler: (Event) throws ->Void)->Observable {
        return Do(source: self.asObservable(), eventHandler: eventHandler)
    }

    public func doOn(onNext onNext: (E throws ->Void)? = nil, onError:(ErrorType throws ->Void)? = nil, onCompleted:(() throws ->Void)? = nil)->Observable {
        return Do(source: self.asObservable()) { e in
            switch e {
                case .Next(let element):
                    try onNext?(element)
                case .Error(let e):
                    try onError?(e)
                case .Completed:
                    try onCompleted?()
            }
        }
    }

    public func doOnNext(onNExt: (E throws->Void))->Observable {
        return self.doOn(onNext: onNext)
    }

    public func doOnError(onError: (ErrorType throws->Void))->Observable {
        return self.doOn(onError: onError)
    }

    public func doOnCompleted(onCompleted: (() throws ->Void))->Observable {
        return self.doOn(onCompleted: onCompleted)
    }
}

class Do: Producer {
    typealias EventHandler = Event throws->Void

    private let _source: Observable
    private let _eventHandler: EventHandler

    init(source: Observable, eventHandler: EventHandler) {
        _source = source
        _eventHandler = eventHandler
    }

    override func fun(observer: O)->Disposable {
        let sink = DoSink(parent: self, observer: observer)
        sink.disposable = _source.subscribe(sink)
        return sink
    }
}

class DoSink: Sink, ObserverType {
    typealias Element = O.E
    typealias parent = Do

    private let _parent: Parent

    init(parent: Parent, observer: O) {
        _parent = parent
        super.init(observer: observer)
    }

    func on(event: Event) {
        do {
            try _parent._eventHandler(event)
            forwardOn(event)
            if event.isStopEvent {
                dispose()
            }
        }catch let error {
            forwardOn(.Error(error))
            dispose()
        }
    }
}

你可能感兴趣的:(do运算)