I need to run several functions and the order in which the functions are executed is very important. I have two non-async functions that need to be run and then two async functions that need to be executed after that. All of the functions must be executed upon the completion of the previous function.
So far I have the following. However, the async functions do not seem to follow the dependencies that I have laid out. Both async functions are executed as soon as the queue begins.
Is there something I am missing? Any help is appreciated! :)
let queue = OperationQueue()
let operation1 = BlockOperation {
nonAsyncFunc1()
}
let operation2 = BlockOperation {
nonAsyncFunc2()
}
let operation3 = BlockOperation {
asyncFunc1()
}
let operation4 = BlockOperation {
asyncFunc2()
}
operation2.addDependency(operation1)
operation3.addDependency(operation2)
operation4.addDependency(operation3)
self.queue.addOperation(operation1)
self.queue.addOperation(operation2)
self.queue.addOperation(operation3)
self.queue.addOperation(operation4)
If you want to run operations serially you have to limit the
maxConcurrentOperationCount
of the queue to 1. This will ensure that only one operation is performed at one time.Also,
BlockOperation
finishes as soon as all of the blocks have returned, for example as soon as yourasyncFunc1
andasyncFunc2
function returns yourBlockOperation
signals completion. So if inside your async function you are calling anyURLSessionTask
the operation would complete before the task completes. You have to create your own async operation by inheritingOperation
class and overridingisAsynchronous
property and signal operation completion manually when your internal async tasks complete.