Rx

RxSwift源码分析(4)——textFiled为何默认响应

2020-10-03  本文已影响0人  无悔zero
textFiled.rx.text
.subscribe(onNext: { (text) in
     print("默认来第一次")
})
  1. 我们直接进入源码,一路走:
extension Reactive where Base: UITextField {
    /// Reactive wrapper for `text` property.
    public var text: ControlProperty<String?> {
        return value
    }
    
    /// Reactive wrapper for `text` property.
    public var value: ControlProperty<String?> {
        return base.rx.controlPropertyWithDefaultEvents(
            ...
        )
    }
extension Reactive where Base: UIControl {
    ...
    internal func controlPropertyWithDefaultEvents<T>(
        editingEvents: UIControl.Event = [.allEditingEvents, .valueChanged],
        getter: @escaping (Base) -> T,
        setter: @escaping (Base, T) -> Void
        ) -> ControlProperty<T> {
        return controlProperty(
            editingEvents: editingEvents,
            getter: getter,
            setter: setter
        )
    }

    public func controlProperty<T>(
        editingEvents: UIControl.Event,
        getter: @escaping (Base) -> T,
        setter: @escaping (Base, T) -> Void
    ) -> ControlProperty<T> {
        let source: Observable<T> = Observable.create { [weak weakControl = base] observer in
                ...
                observer.on(.next(getter(control)))//默认响应

                let controlTarget = ControlTarget(control: control, controlEvents: editingEvents) { _ in
                    if let control = weakControl {
                        observer.on(.next(getter(control)))//事件响应
                    }
                }
                
                return Disposables.create(with: controlTarget.dispose)
            }
            .takeUntil(deallocated)

        let bindingObserver = Binder(base, binding: setter)

        return ControlProperty<T>(values: source, valueSink: bindingObserver)
    }
}
  1. 根据之前讲的RxSwift核心逻辑ControlEventobserver.on(.next(getter(control)))会被调用,就会来到外面的响应,执行默认响应:
.subscribe(onNext: { (text) in
     print("默认来第一次")
})
textFiled.rx.text
.skip(1)
.subscribe(onNext: { (text) in
     print("跳过了第1次响应")
})

还可以用changed

textFiled.rx.text
.changed
.subscribe { (text) in
    print("常用监听输入,默认跳过第1次响应")
}.disposed(by: disposeBag)
上一篇下一篇

猜你喜欢

热点阅读