Add ability to subscribe to multiple keys or any change in a given suite #30
sindresorhus posted onGitHub
This can be useful when you need to handle changes to multiple keys the same.
Should support optionally giving an array or keys or if not given subscribe to all changes.
Something like this:
Defaults.observeAll<T: Codable>(
_ keys: Defaults.Key<T>,
options: NSKeyValueObservingOptions = [.initial, .old, .new],
handler: @escaping () -> Void
) -> DefaultsObservation
Defaults.observeAll<T: Codable>(
suite: UserDefaults = .standard,
options: NSKeyValueObservingOptions = [.initial, .old, .new],
handler: @escaping () -> Void
) -> DefaultsObservation
They should include change objects.
It should also prevent infinite recursion if you call, for example, Defaults[.foo] = true
inside the handler
as that would normally emit an event, which would call it again infinitely. If it doesn't make sense as default, at least there should be an option for this.
The suite:
overload would get all the keys in the given suite and listen to those events. It should not use UserDefaults.didChangeNotification
.
I think it could be useful with an overload that listens to all keys defined in Defaults.Keys
.
Feedback wanted.