Skip to content

Instantly share code, notes, and snippets.

@soxjke
Created February 9, 2020 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soxjke/5bf6d0b9cbb08a110b5c5364b97dac10 to your computer and use it in GitHub Desktop.
Save soxjke/5bf6d0b9cbb08a110b5c5364b97dac10 to your computer and use it in GitHub Desktop.
import Foundation
public class Throttler<T> {
private(set) var value: T? = nil
private var valueTimestamp: Date? = nil
private var interval: TimeInterval
private var queue: DispatchQueue
private var callbacks: [(T) -> ()] = []
public init(_ interval: TimeInterval, on queue: DispatchQueue = .main) {
self.interval = interval
self.queue = queue
}
public func receive(_ value: T) {
self.value = value
guard valueTimestamp == nil else { return }
self.valueTimestamp = Date()
queue.asyncAfter(deadline: .now() + interval) { [weak self] in
self?.onDispatch()
}
}
public func on(throttled: @escaping (T) -> ()) {
self.callbacks.append(throttled)
}
private func onDispatch() {
self.valueTimestamp = nil
sendValue()
}
private func sendValue() {
if let value = self.value { callbacks.forEach { $0(value) } }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment