Created
February 19, 2019 18:06
-
-
Save thexande/f5cf44597e42c60c1332fa47e69af403 to your computer and use it in GitHub Desktop.
throttle implementation class in swift
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
final class Throttler { | |
private var throttleWorkItems: [AnyHashable: DispatchWorkItem] = [:] | |
private var lastDebounceCallTimes: [AnyHashable: DispatchTime] = [:] | |
private let nilContext: AnyHashable = arc4random() | |
/// Delays a closure execution and ensures no other executions are made during deadline | |
/// | |
/// - Parameters: | |
/// - deadline: The timespan to delay a closure execution | |
/// - context: The context in which the throttle should be executed | |
/// - action: The closure to be executed | |
func throttle(deadline: DispatchTime, | |
context: AnyHashable? = nil, | |
action: @escaping () -> Void) { | |
let worker = DispatchWorkItem { [weak self] in | |
guard let myself = self else { return } | |
defer { | |
myself.throttleWorkItems.removeValue(forKey: context ?? myself.nilContext) | |
} | |
action() | |
} | |
DispatchQueue.global(qos: .background).asyncAfter(deadline: deadline, | |
execute: worker) | |
throttleWorkItems[context ?? nilContext]?.cancel() | |
throttleWorkItems[context ?? nilContext] = worker | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment