@Environment for new @Observable macro not creating bindings?

Hi guys,

I am trying to use the new @Observable macro. According to the documentation, this new macro will automatically generate observable properties, but I am having issues using my properties when Bindings are necessary.

Previously I had a setup like this:

class Example: ObservableObject {
    @Published public var myArray = [CustomType]()
}

I initialised one instance of the Example-class in @main

    @StateObject private var exampleClass = Example()

And added as an .environmentObject onto the root view

            ContentView()
                .environmentObject(exampleClass)

In child views I was able to access the @Published property as a binding via

    @EnvironmentObject private var example: Example

    $example.myArray

What I am trying now

This is the setup that I am trying with now:

@Observable class Example {
    public var myArray = [CustomType]()
}

State instead of StateObject in @main

@State private var exampleClass = Example()

.environment instead of .environmentObject

            ContentView()
                .environmentObject(exampleClass)

@Environment instead of @EnvironmentObject

@Environment(Example.self) private var example

This new setup is not letting me access $example.myArray. Is this intended? Could someone explain why?

Post not yet marked as solved Up vote post of davmans Down vote post of davmans
594 views

Replies

I had read that the answer was to mark the shared object with @Binding instead of @State but that was not sufficient. See https://developer.apple.com/forums/thread/735416?answerId=761483022#761483022

In my case I needed to add the equivalent of

@Bindable var profile = profile // must be placed in view body
  • That is different from my use case. I am injecting an environment from the root-view.

Add a Comment