swiftuiswift-composable-architecture

Why am I getting some @Environment updates but not others?


The app I'm working on is SwiftUI (with TCA) and there is a requirement to send some Display Characteristics in our analytics.

Assumption: @Environment values are all updated in the same way, therefore the following code should get the same behaviour for colorScheme as it does for scenePhase.

    @main
    struct MyApp: App {
        @UIApplicationDelegateAdaptor(MobileAppDelegate.self) private var appDelegate

        @Environment(\.colorScheme) var colorScheme
        @Environment(\.scenePhase) var scenePhase

        var body: some Scene {
            WindowGroup {
                RootView(store: root)
                    .onChange(of: colorScheme) {
                        if colorScheme != $0 { appDelegate.viewStore.send(.didChangeColorScheme($0)) }
                    }
                    .onChange(of: scenePhase) {
                        if scenePhase != $0 { appDelegate.viewStore.send(.didChangeScenePhase($0)) }
                    }
                    .onAppear {
                        appDelegate.viewStore.send(.didChangeColorScheme(colorScheme))
                        appDelegate.viewStore.send(.didChangeScenePhase(scenePhase))
                    }
            }
        }
    }

I receive every change to the scenePhase but none for the colorScheme. The onAppear does give me the initial value but if I log the colorScheme in the onChange handler of schenePhase, it never changes from the initial value. This seems to have broken my assumption. Is anyone aware of why and/or how I can get these (and others) to behave the same?


Solution

  • The assumption is still broken. EnvironmentValues are available at different scopes. The documentation for colorScheme and colorSchemeContrast suggests that they are only available from within a view...

    Read this environment value from within a view

    horizontal and vertical size classes also give a hint, but it's less clear

    The value tells you about the amount of space available to the view that reads it.

    There is no hint for the other Display Characteristics but they seem to be at the view level. I have not investigate other EnvironmentValues.