Replies: 1 comment
-
you can make your dependency a class which holds state instead of a struct final class APIEnvironment {
var baseUrl = "someUrl"
}
enum APIEnvironmentKey: DependencyKey {
static var liveValue: APIEnvironment = .init()
}
extension DependencyValues {
var apiEnvornment: APIEnvironment {
get { self[APIEnvironmentKey.self] }
set { self[APIEnvironmentKey.self] = newValue }
}
} so in your code you can mutate @Dependency(\.apiEnvironment) var apiEnvironment
apiEnvironment.baseUrl = "newUrl" the |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am trying to figure out how we might use your form of dependency injection throughout our app - it looks very impressive and useful, but I have some questions.
One hurdle I am trying to understand is the ability to share, and more importantly mutate, state that is used by other dependencies
For example, we currently have an API Environment (production/staging) that is used, among other things, to pick the base URL for our API Client. From our Debug screen we need to have a picker that can choose and update the environment, which is then cached to be loaded next time. Setting this should also change the baseURL on the (live) API client, so that it is used for all future requests.
As a
@Dependency
isnt mutable, would the best way be to have bothvar setAPIEnv: (APIEnv) -> Void
andvar getAPIEnv: () -> APIEnv
interfaces on some AppState DependencyKey? Would it be better to have some kind of stream var as the dependency, so that it can be mirrored to a@Published
var on the debug screen, and also watched by the API client?I have a feeling this may be a misuse of dependencies in general, but it is a use of a shared state singleton in our current app, and I'd like to fully grok the alternatives.
Beta Was this translation helpful? Give feedback.
All reactions