I am trying to understand OperationQueue
's and its advantages over the DispatchQueue
. So when I learn dependencies between Operations I think I can use over the DispatchGroups but I am still trying to understand how can I make them wait for each other without using Semaphore
or DispatchGroup
I started with:
let customQueue = OperationQueue()
let fetchIDOperation = Operation()
let fetchUserPhotoOperation = Operation()
customQueue.maxConcurrentOperationCount = 1
fetchUserPhotoOperation.completionBlock = {
print("photos are fetching")
}
fetchIDOperation.completionBlock = {
let url = URL.init(string: "http://jsonplaceholder.typicode.com/todos/1")!
URLSession.shared.dataTask(with: url) { (data, _, err) in
guard err == nil, let data = data else {
print("err")
return
}
let a = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
print("json > ", a)
}.resume()
}
fetchUserPhotoOperation.addDependency(fetchIDOperation)
customQueue.addOperation(fetchIDOperation)
customQueue.addOperation(fetchUserPhotoOperation)
fetchIDOperation.start()
The output is
ids are fetching
photos are fetching
json > ["completed": 0, "userId": 1, "id": 1, "title": delectus aut autem]
I want that OperationQueue
for photos one should start after the async task done in fetchIDOperation
.
When I search for similar problems in Stackoverflow, in some answers there's referred to be using DispatchSemaphore
. I really loved using the dependency
functionality of the API, so is there an easy way to achieve this way without using semaphore or dispatchgroup?
Thanks in advance