Is it possible to reinject the environment value (managedObjectContext) during runtime

Viewed 47

I inject an NSManagedObjectContext into my view hierarchy the following way.

@main
struct MyApp: App {
  var persistence: Persistence

  var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, persistence.container.viewContext)
        }
    }
}

In the user settings I can switch on/off the CloudKit sync mechanism. The viewContext in the Persistence instance will be reinitialized accordingly. This is working fine. But my complete view hierarchy is still using the old NSManagedObjectContext instance.

Is there any way to update (reinject) the environment value or to reload the whole view hierarchy with the newly instantiated viewContext?

1 Answers

Here is a possible approach - you need to make Persistence as ObservableObject and observe it in app, like

struct MyApp: App {
  @StateObject var persistence: Persistence = Persistence() // or whatever init neede

  ...

and

class Persistence: ObservableObject {
  @Published var container: NSPersistentContainer?

  ...

so whenever you change container the view context will be re-injected into ContentView

Related