Using @Observable with a Binding

I'm using DocumentGroup with a FileDocument.

DocumentGroup(newDocument: MyDocument()) { configuration in
  let documentBinding = configuration.$document
  ...
}

I want to use @Observable for SwiftUI change tracking so I have a class and I set the binding as a property.

@Observable class DocumentWrapper {
    var document: Binding<MyDocument>
}

SwiftUI's change tracking doesn't seem to work through the Binding<MyDocument>. I'm wondering - should this work? Does @Observable work on a property that is a binding?

Observation works if I assign the document directly as a property of DocumentWrapper, but with DocumentGroup, changes need to be written back through the binding to get saved so I can't do that.

Is there a way to make @Observable work with FileDocument?

1 Like

I would separate these out into separate properties in your view and then use onChange to notify the object of the change and act accordingly:

struct View {
  @Binding var document: MyDocument
  var object: MyObject
  
  var body: some View {
    SomeView().onChange(of: document...) { oldValue, newValue in
        object.thingChangedFrom(oldValue, to: newValue)
    }
  }
}