Swift iOS – Understanding DispatchWorkItem notify execute block context

I am exploring DispatchWorkItem to tailor my App requirements. The goal is to write a generic TaskScheduler to schedule actions passed to it in a different thread. The TaskScheduler should also be able to cancel actions no longer required (a good example is cancelling data fetch for cells going out of viewport).

I am achieving this with the help of an id, and a id-to-DispatchWorkItem map. Map helps to cancel actions through id passed. In order to clean the map entries when tasks are completed, I am using notify on DispatchWorkItem.

Is the below code snippet clearing the right map entries? Let’s say, we have 3 actions with ids 1, 2, and 3. Actions 1 and 3 are cancelled, while Action 2 completes its execution. Would below code correctly nullify map entry for Action 2?

self.queue = DispatchQueue(label: "com.serial.queue", qos: DispatchQoS.userInitiated) // Can be .concurrent as well  func schedule(id: UInt, action: @escaping () -> Void) {         cancelAction(with: id)         let dwi = DispatchWorkItem(block: action)         idToDWI[id] = dwi <------------------------- id = 2                  dwi.notify(queue: .main, execute: {             idToDWI[id] = nil <------------------------- id = 2?             print("<<<< Completed \(id)")         })                  self.queue.async(execute: dwi)     } 
Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.