Hi
I have a couple of operations as follows:
class Operation1: Operation
{
private var _executing: Bool = false
private var _finished: Bool = false
var hasError = false
override internal(set) var isExecuting: Bool
{
get
{
return _executing
}
set
{
willChangeValue(forKey: "isExecuting")
_executing = newValue
didChangeValue(forKey: "isExecuting")
}
}
override internal(set) var isFinished: Bool
{
get
{
return _finished
}
set
{
willChangeValue(forKey: "isFinished")
_finished = newValue
didChangeValue(forKey: "isFinished")
}
}
/*
Begins the execution of the operation.
*/
override func main()
{
if isCancelled
{
isFinished = true
return
}
isExecuting = true
// Do something, but results in a failure
self.hasError = true
self.finished()
}
/*
Set the flag to signal a completion operation.
*/
func finished()
{
self.isExecuting = false
self.isFinished = true
}
}
class Operation2: Operation
{
private var _executing: Bool = false
private var _finished: Bool = false
var hasError = false
override internal(set) var isExecuting: Bool
{
get
{
return _executing
}
set
{
willChangeValue(forKey: "isExecuting")
_executing = newValue
didChangeValue(forKey: "isExecuting")
}
}
override internal(set) var isFinished: Bool
{
get
{
return _finished
}
set
{
willChangeValue(forKey: "isFinished")
_finished = newValue
didChangeValue(forKey: "isFinished")
}
}
/*
Begins the execution of the operation.
*/
override func main()
{
if isCancelled
{
isFinished = true
return
}
isExecuting = true
// Do something
self.finished()
}
/*
Set the flag to signal a completion operation.
*/
func finished()
{
self.isExecuting = false
self.isFinished = true
}
}
In my view controller, I construct Operation1 and Operation2 making Operation2 a dendency of Operation1. In the main function of Operation1, I set a property hasError (bool) if an error occurs. The operation1.completionBlock calls cancelAllOperations() is operation1.hasError equal true.
let queue = OperationQueue.main
let operation1 = Operation1()
operation1.completionBlock = {
if operation1.hasError
{
print("Failed, cancelling pending operations.")
queue.cancelAllOperations()
}
}
let operation2 = Operation2()
operation2.completionBlock = {
DispatchQueue.main.async
{
// Do something on UI
}
}
operation2.addDependency(operation1)
queue.addOperation(operation1)
queue.addOperation(operation2)
However, Operation2 continues to execute. What is the best approach to cancel Operation2 if Operation1 fails?
Thanks