KVO

KVO is an Objective-C mechanism. That means that it wasn't built with type safety in mind. This project tries to solve some of the problems.

There are two built in ways this library supports KVO.

// KVO
extension Reactive where Base: NSObject {
    public func observe<E>(type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions, retainSelf: Bool = true) -> Observable<E?> {}
}

#if !DISABLE_SWIZZLING
// KVO
extension Reactive where Base: NSObject {
    public func observeWeakly<E>(type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions) -> Observable<E?> {}
}
#endif

Example how to observe frame of UIView.

WARNING: UIKit isn't KVO compliant, but this will work.

view
  .rx.observe(CGRect.self, "frame")
  .subscribe(onNext: { frame in
    ...
  })

or

view
  .rx.observeWeakly(CGRect.self, "frame")
  .subscribe(onNext: { frame in
    ...
  })

rx.observe

rx.observe is more performant because it's just a simple wrapper around KVO mechanism, but it has more limited usage scenarios

  • it can be used to observe paths starting from self or from ancestors in ownership graph (retainSelf = false)
  • it can be used to observe paths starting from descendants in ownership graph (retainSelf = true)
  • the paths have to consist only of strong properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc.

E.g.

self.rx.observe(CGRect.self, "view.frame", retainSelf: false)

rx.observeWeakly

rx.observeWeakly has somewhat slower than rx.observe because it has to handle object deallocation in case of weak references.

It can be used in all cases where rx.observe can be used and additionally

  • because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown
  • it can be used to observe weak properties

E.g.

someSuspiciousViewController.rx.observeWeakly(Bool.self, "behavingOk")

Observing structs

KVO is an Objective-C mechanism so it relies heavily on NSValue.

RxCocoa has built in support for KVO observing of CGRect, CGSize and CGPoint structs.

When observing some other structures it is necessary to extract those structures from NSValue manually.

Here are examples how to extend KVO observing mechanism and rx.observe* methods for other structs by implementing KVORepresentable protocol.

results matching ""

    No results matching ""