skip to Main Content

I have a button with a .disabled() condition that’s a computed property of my ObservableObject model class. This means I can’t make it @Published.

Something like this:

class MyModel : ObservableObject {
    var isDisabled: Bool {
        if ... {
            return true
        }
        else {
            return false
        }
    }
}

struct SettingsNewsSubscriptionsView : View {
    @ObservedObject var model: MyModel

    var body: some View {
        ...

        Button("Save") {
            Task {
                // Saves to backend asynchronously, then updates MyModel which changes isDisabled.
            }
        }
        .disabled(model.isDisabled)
    }
}

At some point isDisabled is false. When the button is tapped something is saved asynchronously after which MyModel is updated which will result in isDisabled to become true.

Because isDisabled is not @Published, the button does not update once isDisabled becomes true.

How can I trigger the refresh of a SwiftUI View, in this case Button explicitly from within a Task?

2

Answers


  1. You can try making the property stored instead of computed, that way you can use @Published

    Login or Signup to reply.
  2. Call

    model.objectWillChange.send()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search