Skip to content

Instantly share code, notes, and snippets.

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 {
init(handler: @escaping () -> Void,
notificationCenter: NotificationCenter = .default,
notificationName: Notification.Name,
timeInterval: TimeInterval) {
self.handler = handler
self.notificationCenter = notificationCenter
self.timeInterval = timeInterval
selector: #selector(notificationPosted),
name: notificationName,
object: nil)
@objc func notificationPosted() {
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.