Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple notification throttler using DispatchWorkItem
class NotificationThrottler {
let notificationCenter: NotificationCenter
let timeInterval: TimeInterval
let handler: () -> Void
private var workItem: DispatchWorkItem?
deinit {
notificationCenter.removeObserver(self)
}
init(handler: @escaping () -> Void,
notificationCenter: NotificationCenter = .default,
notificationName: Notification.Name,
timeInterval: TimeInterval) {
self.handler = handler
self.notificationCenter = notificationCenter
self.timeInterval = timeInterval
notificationCenter.addObserver(self,
selector: #selector(notificationPosted),
name: notificationName,
object: nil)
}
@objc func notificationPosted() {
workItem?.cancel()
workItem = DispatchWorkItem(block: handler)
//we just created the work item, it is safe to force unwrap in this situation
DispatchQueue.main.asyncAfter(deadline: .now() + timeInterval, execute: workItem!)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.