Last active
April 9, 2018 19:46
-
-
Save cprovatas/07a80afe2d7dbe8269c2f58ce75d5087 to your computer and use it in GitHub Desktop.
Throttle , similar to RxSwift's throttle but can be used on any arbitrary block
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
/// throttle a procedure for the given time interval, operation identifer is used to uniquely identify operation to prevent from firing multiple times | |
private var throttledOperations: Set<String> = [] | |
func dispatchThrottle(_ interval: TimeInterval, operationIdentifier: String, queue: DispatchQueue = .main, _ closure: @escaping () -> Void) { | |
guard !throttledOperations.contains(operationIdentifier) else { return } | |
throttledOperations.insert(operationIdentifier) | |
closure() | |
queue.asyncAfter(deadline: .now() + interval) { | |
throttledOperations.remove(operationIdentifier) | |
} | |
} | |
//usage: | |
dispatchThrottle(2, operationIdentifier: "MyUniqueBlock") { | |
debugPrint("this block will execute only once within the given 2 second window") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment