Created
July 15, 2016 15:40
-
-
Save pepicrft/ba7a1b459634ebf29de0772272b8460b to your computer and use it in GitHub Desktop.
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
import Foundation | |
import RxSwift | |
internal class UserDefaultsObservable<T>: NSObject { | |
// MARK: - Attributes | |
private let userDefaults: NSUserDefaults | |
private let subject: PublishSubject<T?> | |
private let key: String | |
// MARK: - Init | |
public init(key: String, userDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()) { | |
self.userDefaults = userDefaults | |
self.subject = PublishSubject() | |
self.key = key | |
super.init() | |
self.userDefaults.addObserver(self, forKeyPath: key, options: NSKeyValueObservingOptions.New, context: nil) | |
} | |
// MARK: - Public | |
public func rx() -> Observable<T?> { | |
return self.subject | |
} | |
// MARK: - KVO | |
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { | |
self.subject.onNext(self.userDefaults.objectForKey(self.key) as? T) | |
} | |
deinit { | |
self.userDefaults.removeObserver(self, forKeyPath: self.key) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment