SwiftUI - How to pass EnvironmentObject into View Model?

后端 未结 5 2009
甜味超标
甜味超标 2020-12-08 18:56

I\'m looking to create an EnvironmentObject that can be accessed by the View Model (not just the view).

The Environment object tracks the application session data, e

5条回答
  •  渐次进展
    2020-12-08 19:46

    The Resolver library does a nice job to get dependency injection for model classes. It provides a property wrapper @Injected which is very similar in spirit to @EnvironmentObject but works everywhere. So in a model, I would inject a XYZService like this:

    class SomeModel: ObservableObject {
        @Injected var service: XYZService
    }
    

    Such a model I would use as an @EnvironmentObject in the SwiftUI view hierarchy.

    It's a little bit involved because you'll have two dependency-injection containers, Resolver/@Injected for everything that's app-wide/service-like and SwiftUI/@EnvironmentObject in the view hierarchy for everything that relates to views/for view models. But in more complex applications it's a very good fit and worthwile the additional complexity. Much better than singletons/XYZService.shared...

提交回复
热议问题