How to use OperationQueue with async functions?

1.9k views Asked by At

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)
1

There are 1 answers

0
Soumya Mahunt On

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 your asyncFunc1 and asyncFunc2 function returns your BlockOperation signals completion. So if inside your async function you are calling any URLSessionTask the operation would complete before the task completes. You have to create your own async operation by inheriting Operation class and overriding isAsynchronous property and signal operation completion manually when your internal async tasks complete.