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
"Debouncing" is the process by, if there are multiple, rapid calls to a function, only the final one will actually be executed. The perfect example is a web search that happens as the user types - you want to avoid making a call for every character that is entered, but still fire the request without having to hit a "search" button. This way, once the
after
duration expires with no more calls, the block is run. Thecontext
defines the type of the action.