In some scenarios, we all want that the task we want to perform should be cancellable later on. For this kind of behaviour, we already have OperationQueue but the use of It seems difficult for beginners.
Most of us didn't use OperationQueue so frequently and were only familiar with Grand Central Dispatch (GCD). by performing UI operations in the main thread, Dispatch Group, etc. By the use of DispatachWorkItem, we can create some tasks that can be cancelled later on. Here is the example,
let workItem = DispatchWorkItem {
// Here is our task
debugPrint("Task is to print some text...")
}
This is DispatchWorkItem containing a task to print something. To perform this task, we need to make use of DispatchQueue like this by adding delay if required.
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: workItem)
Here is the basic example to add a task and perform it using DispatchQueue. Now to cancel that we need to keep the reference of DispatchWorkItem we created.
import UIKit
var workItemRef: DispatchWorkItem?
let workItem = DispatchWorkItem {
// Here is our task
debugPrint("Task is to print some text...")
}
workItemRef = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: workItem)
/// To Cancel the task we can always use
workItemRef?.cancel()
Here is the full example of this article. We can cancel the task at any point in time by accessing the reference of the work item.
Please share this blog with your friends and colleagues if you like ☺.
Comments
Post a Comment