Sobes.tech
Junior — Middle

How can you cancel a task scheduled with DispatchWorkItem?

sobes.tech AI

Answer from AI

To cancel a task scheduled with DispatchWorkItem in iOS, you use the cancel() method on the DispatchWorkItem object itself.

Example:

let workItem = DispatchWorkItem {
    print("Task execution")
}

DispatchQueue.global().async(execute: workItem)

// Cancel the task
workItem.cancel()

If the task has not yet started, calling cancel() will prevent its execution. Inside the DispatchWorkItem, you can check the cancellation status with isCancelled and respond appropriately, for example:

let workItem = DispatchWorkItem {
    if workItem.isCancelled {
        return
    }
    // main work
}

Thus, task cancellation is performed through the cancel() method of the DispatchWorkItem object.

How can you cancel a task scheduled with… - sobes.tech