Skip to content

Instantly share code, notes, and snippets.

@dev-yong
Last active January 2, 2019 16:42
Show Gist options
  • Save dev-yong/f33b96d468fb47647616706cf90f4253 to your computer and use it in GitHub Desktop.
Save dev-yong/f33b96d468fb47647616706cf90f4253 to your computer and use it in GitHub Desktop.
import Foundation
import Alamofire
private extension Date {
static func second(from referenceDate: Date) -> Int {
return Int(Date().timeIntervalSince(referenceDate).rounded())
}
}
public class Throttler {
//http://danielemargutti.com/2017/10/19/throttle-in-swift/
private var queue: DispatchQueue
private var workItem: DispatchWorkItem = DispatchWorkItem(block: {})
private var previousRun: Date = Date.distantPast
private var maxInterval: Int
private var previousRequest: Request?
init(dispatch: DispatchQueue, seconds: Int) {
self.queue = dispatch
self.maxInterval = seconds
}
func throttle(completion: @escaping ()->Request?) {
workItem.cancel()
previousRequest?.cancel()
workItem = DispatchWorkItem(){ [weak self] in
guard let self = self else { return }
self.previousRun = Date()
self.previousRequest = completion()
}
let delay = Date.second(from: previousRun) > maxInterval ? 0 : maxInterval
queue.asyncAfter(deadline: .now() + Double(delay), execute: workItem)
}
}
public class Debouncer: NSObject {
private var queue: DispatchQueue
private var workItem: DispatchWorkItem = DispatchWorkItem(block: {})
private var previousRequest: Request?
init(dispatch: DispatchQueue) {
self.queue = dispatch
}
func debounce(interval: DispatchTimeInterval, completion: @escaping ()->Request?) {
workItem.cancel()
previousRequest?.cancel()
workItem = DispatchWorkItem() { [weak self] in
guard let self = self else { return }
self.previousRequest = completion()
}
queue.asyncAfter(deadline: .now() + interval, execute: workItem)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment