Swift合并依赖的API调用



我有3个API调用,所有这些都是使用publisher调用的。API A &API B将在API C被调用之前被首先调用。但是API C应该只在API A的响应B满足一些条件。

目前我有这些函数来获得API响应:

func getAPIA() -> AnyPublisher<Response<ResponseA>, Error> { ... }
func getAPIB() -> AnyPublisher<Response<ResponseB>, Error> { ... }
func getAPIC() -> AnyPublisher<Response<ResponseC>, Error> { ... }

我有这些行代码,如果可能的话

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)

如果A和B的响应满足一定条件,则调用APIC,否则不调用APIC。使用Combine可以实现吗?谢谢。

您可以使用flatMap()链接异步操作,以便它们按顺序执行。例如,在代码示例中,您可以这样写:

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())
}

最新更新