Created
February 12, 2019 13:03
-
-
Save natanrolnik/398b1ee0bda3995a8f6a99d2084513ca to your computer and use it in GitHub Desktop.
A simple notification throttler using DispatchWorkItem
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
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