Nice, it should be called "how to implement debounce without rx" ;)
@Bazzeee3 жыл бұрын
How does it work when I have a long running process in the work item and I want it to stop its work whenever it is being cancelled? The only way that process can check for itself if it is cancelled is by keeping a reference to its work item object from self. But as you show in the search example, that work item is being replaced by a new instance.
@AppleProgramming3 жыл бұрын
It is so tricky to do correctly and full of issues that I wouldn't recommend even doing it. Use (NS)Operation or some Combine (if your targets support it) primitive that would work better than this. You'd need something like the following: var request: DispatchWorkItem? request = DispatchWorkItem { print("First step") sleep(2) // work if request?.isCancelled == false { print("Second step") sleep(2) // work } request = nil } searchWorkItem = request let queue = DispatchQueue.global() queue.asyncAfter(deadline: .now() + 0.25, execute: request!) queue.asyncAfter(deadline: .now() + 5) { request?.cancel() request = nil } You need to nil out the reference to request in one way or another. You need an explicit removal outside of just the block itself because if the work gets cancelled then the block is never called and you hold onto the request object. I'll probably be doing a Combine series a little after WWDC so I'll show easier and better solutions for this kind of scenario there. Thanks for watching!
@Bazzeee3 жыл бұрын
@@AppleProgramming Thanks for the thorough reply. I will have a look at Operation and Combine. Love your videos!