Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save alfian0/70dedb9f4df7b406cf8154897f683ef2 to your computer and use it in GitHub Desktop.

Select an option

Save alfian0/70dedb9f4df7b406cf8154897f683ef2 to your computer and use it in GitHub Desktop.
extension Reactive where Base: UserDefaults {
public func `default`<E: Equatable>(_ type: E.Type, _ keyPath: String) -> Observable<E?> {
let center = NotificationCenter.default
let initial = base.object(forKey: keyPath) as? E
let changes = center.rx.notification(UserDefaults.didChangeNotification)
.map { _ in
self.base.object(forKey: keyPath) as? E
}
return Observable<E?>.just(initial)
.concat(changes)
.distinctUntilChanged { previous, next in
guard let previous = previous, let next = next else {
return false
}
return previous == next
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment