nonstrict-hq / CloudStorage

Swift property wrapper to sync settings through iCloud key-value storage
MIT License
233 stars 25 forks source link

@CloudStorage doesn't workin inside @Observable #10

Open iband opened 1 year ago

iband commented 1 year ago

Basically the same issue as with not being able to use @AppStorage inside @Observable (workaround for @AppStorage was suggested here https://medium.com/@davidsteppenbeck/accessing-userdefaults-within-observable-classes-in-ios-17-8cb46ca75689)

tomlokhorst commented 3 months ago

It is correct that @CloudStorage currently doesn't work inside @Observable, same as @AppStorage.

Same as with AppStorage, you can workaround this by manually implementing a getter and setter for a property:

@Observable @MainActor class ViewModel {
    var progress: Double? {
        get {
            access(keyPath: \.progress)
            return CloudStorageSync.shared.double(for: "progress")
        }
        set {
            withMutation(keyPath: \.progress) {
                CloudStorageSync.shared.set(newValue, for: "progress")
            }
        }
    }
}