Skip to content

danielsaidi/ObservablePersistency

Repository files navigation

Project Icon

Version Swift 6.1 Swift UI MIT License

ObservablePersistency

ObservablePersistency is a SwiftUI library that adds persistency support to @Observable, which unlike ObservableObject can't use @AppStorage and SceneStorage property wrappers.

By implementing the ObservablePersisted protocol, an @Observable class gets access to key(_:default:), getValue(for:store:) and setValue(_:for:store:) functions:

@Observable
public class AdminContext: ObservablePersisted {

    private static let adminKey = key("isAdminModeEnabled", default: false)

    /// Whether or not admin mode is enabled.
    public var isAdminModeEnabled = getValue(for: adminKey) {
        didSet { setValue(isAdminModeEnabled, for: Self.adminKey) }
    }
}

This makes it a little cleaner to make a property auto-persisted, compared to explicitly reading from and writing to UserDefaults.

Installation

ObservablePersistency can be installed with the Swift Package Manager:

https://github.com/danielsaidi/ObservablePersistency.git

Support My Work

You can become a sponsor to help me dedicate more time on my various open-source tools. Every contribution, no matter the size, makes a real difference in keeping these tools free and actively developed.

Contact

Feel free to reach out if you have questions or want to contribute in any way:

License

ObservablePersistency is available under the MIT license. See the LICENSE file for more info.

About

This package extends @observable with persistency.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project