Last active
March 20, 2019 14:36
-
-
Save blork/8c45a2b99571719c0f55b39d2ac35434 to your computer and use it in GitHub Desktop.
Simple Debouncer in Swift 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Debouncer.swift | |
// | |
// Created by Sam Oakley on 20/03/2019. | |
// | |
import Foundation | |
class Debouncer { | |
private static var pendingRequestWorkItems: [AnyHashable: DispatchWorkItem] = [:] | |
static func perform(context: AnyHashable, after: DispatchTimeInterval, block: @escaping () -> Void) { | |
let pendingRequestWorkItem = pendingRequestWorkItems[context] | |
pendingRequestWorkItem?.cancel() | |
let requestWorkItem = DispatchWorkItem(block: block) | |
pendingRequestWorkItems[context] = requestWorkItem | |
DispatchQueue.main.asyncAfter(deadline: .now() + after, | |
execute: requestWorkItem) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://open.spotify.com/track/3FzKPS0oVknVlCW3PhxIHl?si=TAs7ZdPvTcGwDnQRGpKq0g