美文网首页
RXSwift序列初探

RXSwift序列初探

作者: leafu | 来源:发表于2019-07-26 17:24 被阅读0次

目录

  1. RXSwift与传统代码的对比。
  2. 事件序列的创建。
  3. Observable可监听序列于Subscribe 事件订阅者

RXSwift与传统代码的对比。

例子UIButton:

传统实现方式

button.addTarget(self,  action: #selector(buttonTapped), for: .touchUpInside)
func buttonTapped() {
    print("button Tapped")
}

RXSwift实现方式

button.rx.tap
    .subscribe(onNext: {
        print("button Tapped")
    })
    .disposed(by: disposeBag)

你不需要使用 Target Action,这样使得代码逻辑清晰可见。

例子KVO:
self.person.addObserver(self, forKeyPath: "name", options: .new, context: nil)

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print("name")
    }

deinit {
        self.person.removeObserver(self, forKeyPath: "name")
    }

RXSwift实现方式

  self.person.rx.observeWeakly(String.self, "name")
            .subscribe {print($0)}
            .disposed(by: dipaseBag)

so easy!是不是,简洁明了!

事件序列的创建。

看了上面的代码,会不会有疑问,这是怎么做到的,那么,接下来就说说.

observable:可监听序列,Observable 可以用于描述元素异步产生的序列。这样我们生活中许多事物都可以通过它来表示(引用官方解释)。

接下来,就创建一个可观察者事件

   let ob = Observable<Any>.create { (obserber) -> Disposable in
            obserber.onNext("Hello")
            obserber.onCompleted()
            obserber.onError(self.mError)
        
            return Disposables.create()
        }
Subscribe: 订阅者,它是与上面observable一对,可以这么理解,产生了监听序列,那么,得有一个地方使用,怎么使用,就是这个Subscribe,observable就相当于报纸生产者,Subscribe相当于订阅报纸的读者
 _ = ob.subscribe(onNext: {
            print($0)
        }, onError: {
            print($0)
        }, onCompleted: {
            print("$0")
        }) {
            print("销毁")
        }

Observable可监听序列于Subscribe 事件订阅者

Observable做了什么?点入方法中查看
extension ObservableType {

    /**
         Creates an observable sequence from a specified subscribe method implementation.
    
         - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
    
         - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
         - returns: The observable sequence with the specified implementation for the `subscribe` method.
         */
    public static func create(_ subscribe: @escaping (RxSwift.AnyObserver<Self.E>) -> Disposable) -> RxSwift.Observable<Self.E>
}

只能看到相关的描述,具体实现看不到,那么在seealso里面有提到create,是不是有这个类文件呢?是的,RXSwift中有个Create.swift类。里面就有一个create方法

extension ObservableType {
    // MARK: create

    /**
     Creates an observable sequence from a specified subscribe method implementation.

     - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)

     - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
     - returns: The observable sequence with the specified implementation for the `subscribe` method.
     */
    public static func create(_ subscribe: @escaping (AnyObserver<E>) -> Disposable) -> Observable<E> {
        return AnonymousObservable(subscribe)
    }
}

揭开一层神秘面纱,在这里调用了一个AnonymousObservable,这个方法是做什么的呢,里面是这样的

final private class AnonymousObservable<Element>: Producer<Element> {
    typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable

    let _subscribeHandler: SubscribeHandler

    init(_ subscribeHandler: @escaping SubscribeHandler) {
        self._subscribeHandler = subscribeHandler
    }

    override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
        let sink = AnonymousObservableSink(observer: observer, cancel: cancel)
        let subscription = sink.run(self)
        return (sink: sink, subscription: subscription)
    }
}

在这个实现里面,用_subscribeHandler匿名函数保存参数对象。

再看 Subscribe做了什么?点入方法中查看
   /**
     Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence.
     
     - parameter onNext: Action to invoke for each element in the observable sequence.
     - parameter onError: Action to invoke upon errored termination of the observable sequence.
     - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
     - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
     gracefully completed, errored, or if the generation is canceled by disposing subscription).
     - returns: Subscription object used to unsubscribe from the observable sequence.
     */
    public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
        -> Disposable {
            let disposable: Disposable
            
            if let disposed = onDisposed {
                disposable = Disposables.create(with: disposed)
            }
            else {
                disposable = Disposables.create()
            }
            
            #if DEBUG
                let synchronizationTracker = SynchronizationTracker()
            #endif
            
            let callStack = Hooks.recordCallStackOnError ? Hooks.customCaptureSubscriptionCallstack() : []
            
            let observer = AnonymousObserver<E> { event in
                
                #if DEBUG
                    synchronizationTracker.register(synchronizationErrorMessage: .default)
                    defer { synchronizationTracker.unregister() }
                #endif
                
                switch event {
                case .next(let value):
                    onNext?(value)
                case .error(let error):
                    if let onError = onError {
                        onError(error)
                    }
                    else {
                        Hooks.defaultErrorHandler(callStack, error)
                    }
                    disposable.dispose()
                case .completed:
                    onCompleted?()
                    disposable.dispose()
                }
            }
            return Disposables.create(
                self.asObservable().subscribe(observer),
                disposable
            )
    }

代码有点长,关键看的地方是AnonymousObserver<E>这个类的里面回调实现,点击进去查看

final class AnonymousObserver<ElementType> : ObserverBase<ElementType> {
    typealias Element = ElementType
    
    typealias EventHandler = (Event<Element>) -> Void
    
    private let _eventHandler : EventHandler
    
    init(_ eventHandler: @escaping EventHandler) {
#if TRACE_RESOURCES
        _ = Resources.incrementTotal()
#endif
        self._eventHandler = eventHandler
    }

    override func onCore(_ event: Event<Element>) {
        return self._eventHandler(event)
    }
    
#if TRACE_RESOURCES
    deinit {
        _ = Resources.decrementTotal()
    }
#endif
}

可以看到,里面同样有个匿名函数进行保存使用_eventHandler。

现在observable与Subscribe都看了一遍,那么他们是怎么进行对接的呢?各自保存的函数在什么时候用的?这个时候,就改伟大的沟通桥梁AnonymousObservableSink。这个才是重点,下一章,了解AnonymousObservableSink。

相关文章

网友评论

      本文标题:RXSwift序列初探

      本文链接:https://www.haomeiwen.com/subject/cjpglctx.html