Skip to content

Instantly share code, notes, and snippets.

@natanrolnik
Created February 12, 2019 13:03
Show Gist options
  • Save natanrolnik/398b1ee0bda3995a8f6a99d2084513ca to your computer and use it in GitHub Desktop.
Save natanrolnik/398b1ee0bda3995a8f6a99d2084513ca to your computer and use it in GitHub Desktop.
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