'Swift Combine dependent API Calls
I have 3 API call, all of them are being called using Publishers. API A & API B will be called first before API C got called. But API C should be called only when the response from API A & B met some conditions.
Currently I have these functions to get the API response:
func getAPIA() -> AnyPublisher<Response<ResponseA>, Error> { ... }
func getAPIB() -> AnyPublisher<Response<ResponseB>, Error> { ... }
func getAPIC() -> AnyPublisher<Response<ResponseC>, Error> { ... }
I have these line of code, it it possible to
Publishers.Zip3(
getAPIA(),
getAPIB(),
getAPIC() // --> How to make this being called based on the response of A and B
).sink(
receiveCompletion: { print($0) },
receiveValue: { [weak self] a, b, c in
// return value
}
).store(in: &cancellable)
If the response of A and B met some conditions, then APIC will be called, otherwise not. Is it achievable using Combine? Thanks.
Solution 1:[1]
You can use flatMap() to chain async operations so the they are executed in sequence. For example in your code sample you could write:
Publishers.Zip(getAPIA(), getAPIB()).flatMap { (responseA: Response<ResponseA>,
responseB: Response<ResponseB>) in
// you can call getAPIC() based on some condtion on responseA or responseA
// and combine all the results in a tuple
Publishers.Zip3(Just(responseA).setFailureType(to: Error.self),
Just(responseB).setFailureType(to: Error.self),
getAPIC())
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christos Koninis |
