How can I invalidate this DispatchWorkItem in Swift?

85 Views Asked by At

I'm making a timer that updates the text as the phone is recording and doing some heavy work with filters. For some reason the work item does not seem to be invalidated because when I go back to my view I have an additional timer updating the text. These keep stacking up every time I go back and restart it.

        recordedTimeQueue = DispatchWorkItem {
            for i in 1 ..< (600) { // 600 max seconds
                usleep(1000000)
                DispatchQueue.main.async {
                    recordedTime?.text = "\(i)"
                }
            }
        }

        DispatchQueue.global().async(execute: recordedTimeQueue!)

When I stop my recording, shouldn't this DispatchWorkItem be tossed out? I even tried making it nil afterwards.

        print("recording stopped")

        recordedTimeQueue?.cancel()

One guess I might have is that I need to create a global bool so I can optionally return out of the for loop, but I don't know why this would be required.

edit: I think I got it, though I don't know if it is technically correct:

        recordedTimeQueue = DispatchWorkItem {
            for i in 1 ..< (600) { // 600 max seconds
                if(recordedTimeQueue?.isCancelled)! { break }
                usleep(1000000)
                DispatchQueue.main.async {
                    recordedTime?.text = "\(i)"
                }
            }
        }
0

There are 0 best solutions below