Skip to content

Instantly share code, notes, and snippets.

@ryanmeisters
Last active February 7, 2017 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanmeisters/b1bff4e16ed2578e43c28961777dce46 to your computer and use it in GitHub Desktop.
Save ryanmeisters/b1bff4e16ed2578e43c28961777dce46 to your computer and use it in GitHub Desktop.
Reactive extension for Realm 2.4 object property observing
extension Reactive where Base: Object {
func observe<T>(_ property: String, type: T) -> Observable<T> {
return Observable.create { observer in
let token = self.base.addNotificationBlock { change in
switch change {
case .change(let properties):
if let change = properties.first(where: { $0.name == property }) {
guard let newValue = change.newValue as? T else {
fatalError("Could not cast observed value \(change.newValue) to \(T.self)")
}
observer.onNext(newValue)
}
case .deleted:
break
case .error(let error):
observer.onError(error)
}
}
return Disposables.create {
observer.onCompleted()
token.stop()
}
}
}
}
@ryanmeisters
Copy link
Author

Doesn't quite work.. Having trouble casting the observed value to T, which is weird. E.g. lldb says change.newValue is Optional<String> but change.newValue as! T crashes with EXC_BAD_INSTRUCTION

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment