网上好多关于OC的KVO介绍。在这里就不详细赘述了。参考KVO原理分析及使用进阶.
在RxSwift中使用todoNameTF.rx.observe(Element.Type, String)注册观察者。
找到具体的实现方法
public func observe<Element: RawRepresentable>(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable<Element?> where Element.RawValue: KVORepresentable {
return self.observe(Element.RawValue.KVOType.self, keyPath, options: options, retainSelf: retainSelf)
.map(Element.init)
}
KVORepresentable找到
public protocol KVORepresentable {
/// Associated KVO type.
associatedtype KVOType
/// Constructs `Self` using KVO value.
init?(KVOValue: KVOType)
}
可以看到进行了初始化。'where'遍历元素的变化。返回self.observe方法。
public func observe<Element>(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable<Element?> {
return KVOObservable(object: self.base, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable()
}
RxCocoa 提供了 2 个可观察序列 rx.observe 和 rx.observeWeakly,它们都是对 KVO 机制的封装,二者的区别如下。
(1)性能比较
rx.observe 更加高效,因为它是一个 KVO 机制的简单封装。
rx.observeWeakly 执行效率要低一些,因为它要处理对象的释放防止弱引用(对象的 dealloc 关系)。
(2)使用场景比较
在可以使用 rx.observe 的地方都可以使用 rx.observeWeakly。
使用 rx.observe 时路径只能包括 strong 属性,否则就会有系统崩溃的风险。而 rx.observeWeakly 可以用在 weak 属性上。
这个参考(键值观察KVO的使用)
网友评论