What is the best practice to have dependency within dependency? #1858
-
I'm thinking about how to deal with dependency. My situation is
and I can't figure out the best way to manage this situation. here is my sample code below. struct SomeFeature: ReducerProtocol {
// ...
@Dependency(\.tokenClient) var tokenClient
func reduce(into state: inout State, action: Action) -> EffectTask<Action> {
// wanna use only token dependency
}
}
struct TokenClient {
// this will handle all the token logic
var token: @Sendable () async throws -> Credential
}
extension TokenClient: DependencyKey {
// static let network: NetworkClient <- I think this can't be injected outside
// I've tried liveValue to be computed property
// like `@Dependency(\.network) var network` inside computed property
// but I can't use network dependency in `doSomeAdditionalFunction1`
static let liveValue: TokenClient = .init(
token: {
// I need some dependency to store token
// and network dependency to request or refresh token
doSomeAdditionalFunction1()
guard let credential = storage.load() else {
return network.requestNewToken()
}
guard credential.isValid else {
return network.refresh(credential)
}
doSomeAdditionalFunction2()
return credential
}
)
private static func doSomeAdditionalFunction1() {
// need some network call
network.doSomething()
}
private static func doSomeAdditionalFunction2() {
// need some dependency
someDependency.doOtherWork()
}
} I have already seen this document. I'm looking forward to your answer. |
Beta Was this translation helpful? Give feedback.
Answered by
stephencelis
Jan 23, 2023
Replies: 1 comment 2 replies
-
@havilog You can use So in the above case, you could reach out to other dependencies directly in your static functions, or even a static computed property: extension TokenClient: DependencyKey {
static var liveValue: Self {
// Expose a dependency to use later:
@Dependency(\.network) var network
return Self(
token: {
doSomeAdditionalFunction1()
guard let credential = storage.load() else {
return network.requestNewToken()
}
// ...
}
)
private static func doSomeAdditionalFunction1() {
// To use the "network" dependency in this function:
@Dependency(\.network) var network
network.doSomething()
}
// ...
}
} |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
havilog
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@havilog You can use
@Dependency
anywhere you need one, just be aware that cyclical dependencies are not supported (where A depends on B depends on A, etc.).So in the above case, you could reach out to other dependencies directly in your static functions, or even a static computed property: