Search code examples
swiftdocument-based

DocumentData / DocumentGroup initializes new instance of @ObservedObject on each change of the documents data in swift


I'm trying to create a Document-Based App, where each new Document has an own instance of Session(), which should not be stored with the document data though:

DocumentGroup(newDocument: DocumentData()) { file in
   ContentView(document: file.$document, session: Session())
}

Session() is defined using

@MainActor
class Session : ObservableObject {
   @Published var sessionName:String? = nil
   @Published var sessionID = UUID()
   // some more to come
   init() {
      print("A new Session has been created: \(self.sessionID.description)
   }
}

Whenever I change something in the Document Data, a new instance of Session() is initiated. Every letter I type makes a new line of

A new Session has been created: 2FCD7F9F-21D6-49BD-B00C-487D86064F08

It works when I do it like this:

@ObservedObject var session = Session()
DocumentGroup(newDocument: DocumentData()) { file in
   ContentView(document: file.$document, session: session)
}

This unfortunately creates one Session() for the whole App - so not one per document.

Mostly I'm wondering WHY this is happening - is this a wanted behavior or rather a bug? It doesn't matter if I initiate the Session() in a subview, the result still stays the same. Any idea how I can solve this problem?


Solution

  • You should change the StateObject to ObservedObject

    StateObject is used for initializing ObservableObjects and ObservedObject is usted to observed already initialized ObservableObjects