Skip to content

Commit

Permalink
Dispatch group vs nested closure
Browse files Browse the repository at this point in the history
  • Loading branch information
codecat15 committed Feb 16, 2021
1 parent 43da128 commit 08f0e26
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import Foundation

/**I hope the video was helpful, please feel free to ask questions and if you are new to the channel then please subscribe, like and share the video with your iOS group

Regards,
Ravi (CodeCat15)
*/

struct Example
{
func work()
{
var arr: [String] = []
let startTime = Date()

// callApiA { (responseFromA) in
// callApiB { (responseFromB) in
// callApiC { (responseFromC) in
// arr.append(responseFromA)
// arr.append(responseFromB)
// arr.append(responseFromC)
// debugPrint(Date().timeIntervalSince(startTime))
// }
// }
// }

let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
callApiA { (responseFromA) in
arr.append(responseFromA)
dispatchGroup.leave()
}

dispatchGroup.enter()
callApiB { (responseFromB) in
arr.append(responseFromB)
dispatchGroup.leave()
}

dispatchGroup.enter()
callApiC { (responseFromC) in
arr.append(responseFromC)
dispatchGroup.leave()
}

dispatchGroup.notify(queue: .main) {
debugPrint(Date().timeIntervalSince(startTime))
}
}

func callApiA(completion:@escaping(String)->Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(1), execute: {
completion("data from service A")
})
}

func callApiB(completion:@escaping(String)->Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(2), execute: {
completion("data from service B")
})
}

func callApiC(completion:@escaping(String)->Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(3), execute: {
completion("data from service C")
})
}
}

let obj = Example()
obj.work()
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios' buildActiveScheme='true'>
<timeline fileName='timeline.xctimeline'/>
</playground>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.

0 comments on commit 08f0e26

Please sign in to comment.