-
I'm working on a codebase where many instances of struct FooClient {
let doSomethingWithBar: @Sendable async (Bar) -> Void
}
extension FooClient {
func decodeBarAndDoSomethingWithIt(_ data: Data, decoder: JSONDecoder = .iso8601) async throws {
let bar = try decoder.decode(data, as: Bar.self)
await doSomethingWithBar(bar)
}
} The implementation is not really relevant, but what's relevant is whether injecting decoder everywhere is a good idea or whether we'd benefit from extension JSONDecoder: DependencyKey {
public static let liveValue: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return decoder
}()
}
// later...
extension FooClient {
func decodeBarAndDoSomethingWithIt(_ data: Data) async throws {
@Dependency(\.jsonDecoder) var decoder
let bar = try decoder.decode(data, as: Bar.self)
await doSomethingWithBar(bar)
}
} Does this make sense? FooClient will only be called from reducers so the dependency will always be found, but what boggles me a bit is that the dependency should always be live, including in tests and previews. Is that considered good etiquette, or am I misusing I can think of other use cases for live-only dependencies such as date or number formatters, and it actually kinda makes sense for those to exist like this because they would need I appreciate any thoughts on this. Note: I freehanded this code so there might be syntactical inconsistencies. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It is totally fine to use But, I do have a question. Is there ever a time that a non- However, if non- |
Beta Was this translation helpful? Give feedback.
It is totally fine to use
@Dependency
in the way you have done here, and it's totally fine to have the test/preview/live value all be the same thing. You can even use@Dependency
outside the context of a reducer, which is why we may open source it as a separate library someday soon.But, I do have a question. Is there ever a time that a non-
JSONDecoder.iso8601
is used? If everything should be using it, then maybe it's ok just to have a global value that all code can use?However, if non-
.iso8601
values can be used, then I think what you have done here is fine, and again it is OK for the test/preview/live value to all be the same thing.