当两个API调用完成时,我当前正在使用DispatchGroup来接收通知,然后将两个响应组合到一个对象中,然后在完成处理程序中返回。
这适用于rest api,但一旦我将其用于两个流式调用,应用程序就会崩溃,因为持续触发/不均衡的dispatchGroup.leave计数。
我还有什么方法可以实现我的目标,或者我可以做些什么来继续使用DispatchGroup?下面是一个快速的例子来展示我正在做的事情。
func fetchPets(completion: @escaping (Result<[Pet], Error>) -> Void) {
let dispatchGroup = DispatchGroup()
let dogs: [Dog] = []
let cats: [Cat] = []
// Make streaming call 1
dispatchGroup.enter()
fetchDogs(completion: () -> Void) {
// Do something (transform data) and add dogs to array
dispatchGroup.leave()
}
// Make streaming call 2
dispatchGroup.enter()
fetchCats(completion: () -> Void) {
// Do something (transform data) and add cats to array
dispatchGroup.leave()
}
// Combine both responses once both calls complete
dispatchGroup.notify(queue: .main) {
// Do something with the stuff
let pets = Pet(...)
completion(pets)
}
}
您可以手动计数它们中的两个是否完成
class YourClass {
var totalRequest = -1
var requestLoaded = -1
func fetchPets() {
fetchDogs()
fetchCats()
}
func fetchDogs() {
totalRequest += 1
APICall.getDogsData { (response) in
self.requestLoaded += 1
// Do something (transform data) and add dogs to array
self.checkIfAllRequestLoaded()
}
}
func fetchCats() {
totalRequest += 1
APICall.getCatsData { (response) in
self.requestLoaded += 1
// Do something (transform data) and add cats to array
self.checkIfAllRequestLoaded()
}
}
// Combine both responses once both calls complete
func checkIfAllRequestLoaded() {
if requestLoaded == totalRequest {
// Do something with the stuff
}
}
}