Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make @Default usable in an ObservableObject #48

Open
lisindima opened this issue May 25, 2020 · 3 comments
Open

Make @Default usable in an ObservableObject #48

lisindima opened this issue May 25, 2020 · 3 comments
Labels
enhancement New feature or request

Comments

@lisindima
Copy link

lisindima commented May 25, 2020

Good afternoon and thanks for this amazing package. I came across a small error, I can not get the view to be updated when I reset the value to default. When I close the application and open it again, I see that the value is written and is equal to the default.

class SessionStore: ObservableObject {
    @Default(.loginModel) var loginModel
}

extension Defaults.Keys {
    static let loginModel = Key<LoginModel?>("loginModel", default: nil)
}

Button(action:  {
    sessionStore.loginModel = nil 
}) {
     HStack {
          Image(systemName: "flame")
                   .frame(width: 24)
          Text("Выйти из аккаунта")
       }.foregroundColor(.red)
}
@sindresorhus
Copy link
Owner

sindresorhus commented Jun 4, 2020

You cannot use @Default in an ObservableObject. It's meant to be used in a View.

I agree, it would be useful to allow this, but it's currently not possible to replicate the functionality of @Published, since it uses internal runtime inspection. More info here: https://twitter.com/olebegemann/status/1222866304786423808


There are ways to make this partly work: https://stackoverflow.com/a/59039333/64949 But I'm inclined to wait for WWDC before doing anything more, as I'm hoping it will bring the improvements needed.

@sindresorhus sindresorhus changed the title The view is not updated when the value is reset to default Make @Default usable in an ObservableObject Jun 4, 2020
@sindresorhus sindresorhus added the enhancement New feature or request label Jun 4, 2020
@sindresorhus
Copy link
Owner

Unrelated, but you don't need default: nil when the type is optional.

@sindresorhus
Copy link
Owner

From macOS 11.3 beta 2 release notes:

AppStorage property wrappers now work as expected when contained inside an ObservableObject , causing the system to emit the objectWillChange publisher. (65562845)

So we could maybe wrap @AppStorage or something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants