Detect when @EnvironmentObject variable has been initialised inside property wrapper

I'm making a custom property wrapper, and inside of it is an @EnvironmentObject variable. A dummy version of it looks like this:

Code Block swift
@propertyWrapper
struct Store: DynamicProperty {
    @EnvironmentObject var centralStore: CentralStore
    var wrappedValue: CentralStore {
        centralStore
    }
    @State var value: Int = 0
    var cancellable: AnyCancellable?
    init() {
        cancellable = centralStore
            .statePublisher
            .filter { (n: Int) in n % 2 == 0 }
            .sink { [_value] n in _value.wrappedValue = n }
    }
}


When I run this, the program crashes with "Fatal error: No ObservableObject of type CentralStore found." (and I double-checked that I injected it into the view hierarchy with environmentObject(_:)). It seems like the initialisation of the @Store property wrapper is run before centralStore is found - so accessing it leads to a fatalError.

Is there a way to detect that my CentralStore environment object has been found, so that I can subscribe to the statePublisher there? (property observers don't seem to work)

I don't think that there's currently a way to explore and examine (programmatically) what is in the environment - so there's no obvious way to verify that the object you're expecting to be in the environment was injected.

To deal with this little quirk, the pattern that I've seen used in some code is to have an top-level View that explicitly injects the relevant environment object, often as a an explicit parameter to that view, and then use that as a base point upon which you can assume (safely) that all subviews from here will have the relevant pieces you need.

Detect when @EnvironmentObject variable has been initialised inside property wrapper
 
 
Q