Created
January 20, 2021 15:25
-
-
Save andr3a88/ddeb029a4bcd903bd0cfc62e22663231 to your computer and use it in GitHub Desktop.
Throttler
This file contains 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 | |
| |
public class Throttler { | |
private var workItem = DispatchWorkItem(block: {}) | |
private var previousRun = Date.distantPast | |
private let queue: DispatchQueue | |
private let minimumDelay: TimeInterval | |
| |
public init(minimumDelay: TimeInterval, queue: DispatchQueue = DispatchQueue.main) { | |
self.minimumDelay = minimumDelay | |
self.queue = queue | |
} | |
| |
public func throttle(_ block: @escaping () -> Void) { | |
cancel() | |
| |
// Re-assign workItem with the new block task, resetting the previousRun time when it executes | |
workItem = DispatchWorkItem { | |
[weak self] in | |
self?.previousRun = Date() | |
block() | |
} | |
| |
// If the time since the previous run is more than the required minimum delay | |
// => execute the workItem immediately | |
// else | |
// => delay the workItem execution by the minimum delay time | |
let delay = previousRun.timeIntervalSinceNow > minimumDelay ? 0 : minimumDelay | |
queue.asyncAfter(deadline: .now() + Double(delay), execute: workItem) | |
} | |
public func cancel() { | |
// Cancel any existing work item if it has not yet executed | |
workItem.cancel() | |
} | |
} | |
// Usage | |
private var throttler = Throttler(minimumDelay: 0.50) | |
navigation?.searchTextfield.onTextDidChange = { [weak self] text in | |
guard let self = self else { return } | |
self.throttler.throttle { | |
guard let text = text, text.count > 1 else { | |
self.reloadTable() | |
self.searching = false | |
return | |
} | |
if !self.searching { | |
self.reloadTable(loading: true) | |
self.searching = true | |
} | |
if let lat = self.currentLocation?.latitude, let lon = self.currentLocation?.longitude { | |
self.reloadTable(text: text, proximity: "\(String(lat)),\(String(lon))") | |
} else { | |
self.reloadTable(text: text, proximity: self.viewModel.suggestProximity()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment