swift ui handle property changed in observableObject

Viewed 245

so - I have a text field on a screen - the data loads asynchronously - so I've created and ObservableObject with a published field, and successfully bind it to the view:

class Blah : ObservableObject
{
    @Published var value : Double? = nil
 
    init()
    { 
         load_variable_async().then {result in self.value = result }
    }
}

which works perfectly - the view reflects the value of the variable and everything.
But - I want it to work both ways. Published seems to be a bidirectional wrapper, so I want to add something like this:

init()
{
    load_variable_async().then {result in self.value = result }
    value.when_changed { new_value in asynchronously_save( variable) }
}

and I can't find any way of doing it. Everything I google for puts a sink or some call to a save in the view - which seems completely wrong to me... if I'm reading it in one place, I want to be writing it in the same place - and if I'm already binding the variable to a textfield for instance, and bindings go both ways, then enough connections have already been made

So what am I doing wrong? How do react to value being set, inside my "model" object without explicitly putting some sort of save or other action into the view?

1 Answers

So I found the solution I wanted - the binding from model -> textfield was always working, but the value from textfield -> model I couldn't get working. The magic seems to be this keyword "willSet"

   @Published var value : Double? = nil {
       willSet( new_value ) {
             print("going to save asynchronously now")
       }}

works magically.

Related