Last active
February 7, 2017 21:24
-
-
Save ryanmeisters/b1bff4e16ed2578e43c28961777dce46 to your computer and use it in GitHub Desktop.
Reactive extension for Realm 2.4 object property observing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't quite work.. Having trouble casting the observed value to
T
, which is weird. E.g. lldb sayschange.newValue is Optional<String>
butchange.newValue as! T
crashes with EXC_BAD_INSTRUCTION