Daily iOS
Concurrency

Canceling delayed work

You scheduled DispatchQueue.main.asyncAfter(deadline: .now() + 2) { showTooltip() }, and if the user leaves the screen within 2 seconds it has to be canceled. How would you do that with GCD?

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

Wrap the closure in a DispatchWorkItem, pass it to asyncAfter, keep it in a property, and call cancel() when the user leaves the screen. Keep items per key and cancel the previous one when scheduling a new one, and you get a debounce too.

Share a question