Singleton Dispatch不等待其他组



我正在尝试等待来自不同类的所有函数完成将数据附加到数组后再继续。

我为dispath组创建了一个singleton类。当来自不同类的所有组都离开时,它不会通知result((,而是单独执行。

class parralelRunner {
let dispatchGroup = DispatchGroup()
result(){
dispatchGroup.notify(queue: .main) {
print("All functions complete 👍")
}
}
}
class run1 {
func start(){
callAPI(){
filterresult()
}
}
callAPI(completion: (JSON)){
Alamofire.request("url", headers: headers).responseJSON { response in
if response.result.isSuccess{
completion(JSON(response.result.value!))
}else{
print("Binance - Couldn't import Request: Please check your internet connection")
}
}
}

func filterresult(){
parralelRunner.dispatchGroup.enter()
for .... {
}
parralelRunner.dispatchGroup.leave()
parralelRunner.result()
}
}

class run2 {
func start(){
callAPI(){
filterresult()
}
}
callAPI(completion: (JSON)){
Alamofire.request("url", headers: headers).responseJSON { response in
if response.result.isSuccess{
completion(JSON(response.result.value!))
}else{
print("Binance - Couldn't import Request: Please check your internet connection")
}
}
}

func filterresult(){
parralelRunner.dispatchGroup.enter()
for .... {
}
parralelRunner.dispatchGroup.leave()
parralelRunner.result()
}
}

parralelRunner.result()的调用只能调用一次。并且需要在每个异步进程开始时对enter进行调用,并在调用完成后对leave进行相应的调用。

您需要做的第一件事是将run1run2重构为以下内容:

class run1 {
func start(){
parralelRunner.dispatchGroup.enter()
callAPI(){ JSON in
if let JSON = JSON {
filterresult()
}
parralelRunner.dispatchGroup.leave()
}
}
callAPI(completion: (JSON?)){
Alamofire.request("url", headers: headers).responseJSON { response in
if response.result.isSuccess{
completion(JSON(response.result.value!))
}else{
print("Binance - Couldn't import Request: Please check your internet connection")
completion(nil)
}
}
}
func filterresult() {
for .... {
}
}
}

那么,无论使用run1run2,都需要类似的东西:

run1.start()
run2.start()
parralelRunner.result()

相关内容

  • 没有找到相关文章

最新更新