Last active
May 13, 2021 09:25
-
-
Save Ariandr/a7d77031f2d3f1440cdcb9ecb8f1644d to your computer and use it in GitHub Desktop.
A simple Swift class that lets you debounce any closures
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
| 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