11import Foundation
2+ import Combine
23
34// MARK: - Public API
45
@@ -7,6 +8,15 @@ import Foundation
78public struct GeneralAppSettingsStorage {
89 private let fileStorage : FileStorage
910
11+ /// This subject is used internally to force a refresh of any settings publisher.
12+ /// Every time the underlying settings change, we should emit a value here.
13+ ///
14+ /// Since there is no guarantee that there will be a single instance of GeneralAppSettingsStorage,
15+ /// we use a shared static property so that any instance that writes changes to settings emits a
16+ /// value that would refresh the data on any other instance.
17+ ///
18+ private static let refreshSubject = CurrentValueSubject < Void , Never > ( ( ) )
19+
1020 public init ( fileStorage: FileStorage = PListFileStorage ( ) ) {
1121 self . fileStorage = fileStorage
1222 }
@@ -18,6 +28,15 @@ public struct GeneralAppSettingsStorage {
1828 return settings [ keyPath: setting]
1929 }
2030
31+ /// Returns a publisher that emits updates every time the value at the given key path changes.
32+ ///
33+ public func publisher< T> ( for setting: KeyPath < GeneralAppSettings , T > ) -> AnyPublisher < T , Never > where T: Equatable {
34+ settingsPublisher
35+ . map ( setting)
36+ . removeDuplicates ( )
37+ . eraseToAnyPublisher ( )
38+ }
39+
2140 /// Writes the value to the stored setting for the given key path
2241 ///
2342 public func setValue< T> ( _ value: T , for setting: WritableKeyPath < GeneralAppSettings , T > ) throws {
@@ -32,10 +51,20 @@ public struct GeneralAppSettingsStorage {
3251 loadOrCreateGeneralAppSettings ( )
3352 }
3453
54+ /// Returns a publisher that emits updates every time the settings change..
55+ ///
56+ public var settingsPublisher : AnyPublisher < GeneralAppSettings , Never > {
57+ Self . refreshSubject
58+ . map ( { settings } )
59+ . removeDuplicates ( )
60+ . eraseToAnyPublisher ( )
61+ }
62+
3563 /// Writes a new GeneralAppSettings object to storage
3664 ///
3765 public func saveSettings( _ settings: GeneralAppSettings ) throws {
3866 try saveGeneralAppSettings ( settings)
67+ Self . refreshSubject. send ( ( ) )
3968 }
4069}
4170
0 commit comments