I’m still working on various solutions to service dependencies.
But my current thinking is that I might forgo environmentObject (and its issues) altogether and consider using a variant of my dependency injection system (Resolver) in SwiftUI. Something like…
struct ContentView: View { @InjectedObject var user: UserService var body: some View {
VStack {
Text(user.name)
Text(user.data ?? "n/a")
Button(action: {
self.user.update()
}) {
Text("Update")
}
}
}
}
The InjectedObject wrapper is a version of my Injected wrapper that performs automatic dependency injection using property wrapper annotation while at the same time exposing an ObservableObject to SwiftUI.
UserService might look like…
class UserService: ObservableObject { @Published var name = "Michael"
@Published var data: String? @Injected var anotherDependency: SecondDependentService func update() {
anotherDependency.fetch {
self.data = $0
}
}
}
Where SecondDependentService is a behind-the-scenes service and not necessarily a SwiftUI ObservableObject.