Unique container per macOS window #229
-
Hello 👋 I'm wondering if there is a recommended pattern to create a Basically, I'm storing some global application state in my services, but I would like this state to be unique per eg. this is very simplified example. But the problem is that @Observable class TimeService {
var currentTime = Date(timeIntervalSince1970: 0)
} extension Container {
var timeService: Factory<TimeService> {
Factory(self) { TimeService() }
}
} @Observable class ClockViewModel {
@ObservationIgnored
@Injected(\.timeService) var timeService
var time: Double {
get {
timeService.currentTime.timeIntervalSince1970
}
set {
timeService.currentTime = Date(timeIntervalSince1970: newValue)
}
}
} struct ClockView: View {
@State var viewModel = ClockViewModel()
var body: some View {
Slider(value: $viewModel.time, in: 0...120)
}
} @main
struct ExampleApp: App {
var body: some Scene {
WindowGroup {
ClockView()
}
}
} Thank you for any help! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You can pass a container along in view initializers, or via the Environment, but if you use any of the injected property wrappers those all interact with the global shared state for Container. There's no differentiation per scene. |
Beta Was this translation helpful? Give feedback.
You can pass a container along in view initializers, or via the Environment, but if you use any of the injected property wrappers those all interact with the global shared state for Container. There's no differentiation per scene.