1

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?

1
  • 1
    Use StateObject to initialize not ObservedObject Commented Aug 22, 2022 at 19:00

1 Answer 1

2

You should change the StateObject to ObservedObject

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.