RxSwift源码分析(4)——textFiled为何默认响应
2020-10-03 本文已影响0人
无悔zero
- 在订阅
textFiled.rx.text
这个序列的时候,会发现默认响应一次:
textFiled.rx.text
.subscribe(onNext: { (text) in
print("默认来第一次")
})
- 我们直接进入源码,一路走:
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)
}
}
- 根据之前讲的RxSwift核心逻辑和ControlEvent,
observer.on(.next(getter(control)))
会被调用,就会来到外面的响应,执行默认响应:
.subscribe(onNext: { (text) in
print("默认来第一次")
})
- 有时候默认响应没有必要,或者想要跳过前几次响应的话,我们可以用
skip
(源码可以看下一篇RxSwift源码分析(4)——skip):
textFiled.rx.text
.skip(1)
.subscribe(onNext: { (text) in
print("跳过了第1次响应")
})
还可以用changed
:
textFiled.rx.text
.changed
.subscribe { (text) in
print("常用监听输入,默认跳过第1次响应")
}.disposed(by: disposeBag)