-
I would like to make a nested function call within a client. For instance, I need to invoke the second function call inside the first function call. While we can certainly use a third function to handle the request, are there any other alternatives available? public struct ApiClient: Sendable {
public var firstRequest: @Sendable () async throws -> String
public var secondRequest: @Sendable () async throws -> String
}
extension ApiClient: DependencyKey {
public static let liveValue = Self(
firstRequest: {
return try await secondRequest // ??
},
secondRequest: {
return try await thirdRequest()
}
)
static func thirdRequest() async throws -> String {
return ""
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
If you want to use the struct-style of dependency then what you have sketched out is probably the best way to handle it. If that style is too onerous then you could try going back to the protocol style. Also, is there a chance that Like this: public struct ApiClient: Sendable {
public var firstRequest: @Sendable () async throws -> String
public func secondRequest() async throws -> String {
// Do stuff
return try await self.firstRequest()
}
} Should people be allowed to override |
Beta Was this translation helpful? Give feedback.
Yes, you can do that, but you have to be aware of all the caveats of using
@Dependency
in an escaping closure like that, unless you are using a single-entry point system such as the Composable Architecture.Here are some articles from the docs for you to learn about these subtleties:
I personally think using a helper function to share the logic is better, and avoids the caveats detailed in the above articles.
There's also a chance that a protocol version of this dependency is a better fit since…