What is the benefit of using a dispatch group with calls in the loop? I am using alamo fire as my network layer. The scenario is that I want to fetch data from the server in chunks and once all calls are done I can move forward. Do I really need to use dispatch group or simple looped calls will work?
for _ in 1...calls {
callFetchTransaction(offset: self.offset, limit: self.transactionsLimit, calls: calls)
}
and this is what is inside my function:
var listOfIdsToSort = [String:Date]()
func callFetchTransaction(offset:Int,limit:Int,calls:Int) {
TransactionsModel.reportTransactions(offset: offset, limit: limit, success: { (transactions) in
ACTIVITYCALL += 1
print("CurrentOffset \(offset), with limit\(limit)")
print("ACTIVITY CALL \(ACTIVITYCALL)")
for transaction in transactions {
self.listOfIdsToSort[transaction.id!] = transaction.createdAt!
}
if ACTIVITYCALL == calls {
TransactionsModel.assignSequenceNumbers(dictOfIds: self.listOfIdsToSort) {
self.didCompleteProgressAndSync(duration: 2.0)
print("sync time after --- \(Date().timeIntervalSince1970)")
}
return
} else if ACTIVITYCALL < calls {
self.currentSyncingProgress += self.perActivityPercentage
DispatchQueue.main.async {
self.updateProgressBar(value: self.currentSyncingProgress)
}
}
}) { (response, statusCode) in
self.callFetchTransaction(offset: offset, limit: limit, calls: calls)
}
It seems to work fine but I want to know if there are some benefits of dispatch group or flaws in this approach.
DispatchGroup
with correspondingenter()
&leave()
will let you know onnotify()
when ALL calls are completed, which you can't do with a simple "for loop". That's big advantage. – Larme Feb 23 at 10:17ACTIVITYCALL += 1
and checkingACTIVITYCALL == calls
for every API response calls all these cumbersome logics can be avoided with simple 3 or 4 statements of dispatch group, Also you are checking all these conditions only in success closure what if API fails ? Then you if conditionACTIVITYCALL == calls
will never be satisfied :) Can you achieve what you can achieve very easily with dispatch group using loops or by blocking threads probably you can, should you do it? Never. Use dispatch group it is intended for monitoring completion of async tasks – Sandeep Bhandari Feb 23 at 10:25