Created
February 9, 2020 19:14
-
-
Save soxjke/5bf6d0b9cbb08a110b5c5364b97dac10 to your computer and use it in GitHub Desktop.
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<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