I have a series of HTTP requests made sequentially using Alamofire in a list of functions called in a main function, runTask()
that I want to have the ability to stop. So, I set up the runTask()
function call in a DispatchWorkItem
for each of the task I need to run and store the work item in an array like so:
taskWorkItems.append(DispatchWorkItem { [weak self] in
concurrentQueue!.async {
runTask(task: task)
}
})
Then, I iterate of the array of work items and call the perform()
function like so:
for workItem in taskWorkItems {
workItem.perform()
}
Finally, I have a button in my app that I want to cancel the work items when tapped, and I have the following code to make that happen:
for workItem in taskWorkItems {
concurrentQueue!.async {
workItem.cancel()
print(workItem.isCancelled)
}
}
workItem.isCancelled
prints to true
; however, I have logs set up in the functions called by runTask()
and I still see the functions executing even though workItem.cancel()
was called and workItem.isCancelled
prints true
. What am I doing wrong and how can I stop the execution of my functions?
isCancelled
property is pointing out if the task is currently cancelled. If you cancel a WorkItem the task is totally cancelled if the execution has not started. If it started and is cancelled, theisCancelled
property will indicatetrue
, so you may implement your cancellation logic. There is a previous answer on how to cancel requests on Alamofire https://mcmap.net/q/423877/-cancel-a-request-alamofire You should execute therequest.cancel()
function into your Work Item logic if necessary. – Explanation