pableiros
pableiros

Reputation: 16022

How to run async Operation

For example, I have this custom operation:

class CustomOperation: Operation {

    override init() {
        super.init()
        self.qualityOfService = .userInitiated
    }

    override func main() {
        // ..
    }
}

And this is what I'm doing to run the CustomOperation:

let customOperation = CustomOperation()
customOperation.completionBlock = { print("custom operation finished") }
customOperation.start()

I have a few CustomOperations trying to run at the same time. Is anyway to run it async without creating an OperationQueue for each CustomOperation? Because the isAsynchronous property is read only.

Upvotes: 0

Views: 339

Answers (1)

Lou Franco
Lou Franco

Reputation: 89142

You don't have to create a queue for each operation. You can put them all in the same queue. The queue's maxConcurrentOperationCount determine's how many are run simultaneously.

If you don't want to use a queue at all, you need to override start() and isAsynchronous() and have start() start a thread and run. There is more you need to do than that (read the docs)

https://developer.apple.com/reference/foundation/operation

Go to the "Methods to Override Section"

If you are creating a concurrent operation, you need to override the following methods and properties at a minimum:

  • start()
  • isAsynchronous
  • isExecuting
  • isFinished

In a concurrent operation, your start() method is responsible for starting the operation in an asynchronous manner. Whether you spawn a thread or call an asynchronous function, you do it from this method. Upon starting the operation, your start() method should also update the execution state of the operation as reported by the isExecuting property. You do this by sending out KVO notifications for the isExecuting key path, which lets interested clients know that the operation is now running. Your isExecuting property must also provide the status in a thread-safe manner.

Upvotes: 1

Related Questions