Skip to main content

Posts

Showing posts from August, 2021

Cancellable Task with Dispatch Work Item | iOS | Swift

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 referen