Post

Replies

Boosts

Views

Activity

ObservableObject as a singleton vs EnvironmentObject
Any opinions on creating ObservableObjects as a singleton vs injecting a objects as EnvironmentObjects? Example 1, the singleton, works, but I'm not a fan // MARK: - Example 1 class Singleton: ObservableObject { @Published var someProperty: Bool static var shared = Singleton() private init() { someProperty = true } } struct SomeView: View { @ObservedObject var singleton = Singleton.shared var body: some View { Text("Hello Woild") } } // MARK: - Example 2 class SomeClass: ObservableObject { @Published var someProperty: Bool init() { someProperty = true } } struct SomeApp: App { @StateObject var someClass = SomeClass() var body: some Scene { WindowGroup { SomeView() .environmentObject(someClass) } } } struct SomeOtherView: View { @EnvironmentObject var someClass: SomeClass var body: some View { Text("Hello Woild") } }```
3
3
4.4k
Apr ’22