Skip to content

Instantly share code, notes, and snippets.

@Ariandr
Last active May 13, 2021 09:25
Show Gist options
  • Select an option

  • Save Ariandr/a7d77031f2d3f1440cdcb9ecb8f1644d to your computer and use it in GitHub Desktop.

Select an option

Save Ariandr/a7d77031f2d3f1440cdcb9ecb8f1644d to your computer and use it in GitHub Desktop.
A simple Swift class that lets you debounce any closures
import Foundation
class Debouncer {
private let queue: DispatchQueue
private var task: DispatchWorkItem?
private(set) var hasPerformedWorkAfterCancel = false // helper property which is needed for some use cases to understand if the work was done
init(queue: DispatchQueue = DispatchQueue.main) {
self.queue = queue
}
func debounce(interval: TimeInterval, work: @escaping () -> Void) {
self.task?.cancel()
let task = DispatchWorkItem { [weak self] in
work()
self?.hasPerformedWorkAfterCancel = true
}
self.task = task
queue.asyncAfter(deadline: DispatchTime.now() + interval, execute: task)
}
func cancel() {
self.task?.cancel()
hasPerformedWorkAfterCancel = false
}
var isDebouncing: Bool {
guard let task = task, !task.isCancelled else {
return false
}
return true
}
}
// MARK: - Usage
// private let searchDebouncer = Debouncer()
// ...
// searchDebouncer.debounce(interval: 0.3) { [weak self] in
// self?.sendSearchRequest()
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment