View Models & Environment Property Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Using @Environment & ViewModels

In Lesson 2, you saw how @State works with @Observable to implement the MVVM architecture. You can declare and instantiate your view model object as a @State property in a view, then pass it to a subview. That subview doesn’t need any property wrapper if it’s only reading values from the view model object.

struct TheMetApp: App {
@State var store = TheMetStore()
  var body: some Scene {
    WindowGroup {
      ContentView()
        .environment(store)
    }
  }
}
@Environment(TheMetStore.self) var store
#Preview {
  ContentView()
    .environment(TheMetStore())
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo 1