nonstrict-hq / CloudStorage

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

@CloudStorage doesn't workin inside @Observable #10

Open iband opened 11 months ago

iband commented 11 months 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 2 weeks 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")
            }
        }
    }
}