Last active
January 24, 2019 02:58
-
-
Save ha1f/4bc7a78bbd19a756319884e132b7e7e8 to your computer and use it in GitHub Desktop.
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
import Foundation | |
/// Debouncer is useful for situations like following. | |
/// If we want to execute action n sec after the last trigger. | |
public final class Debouncer<T> { | |
let dispatchQueue: DispatchQueue | |
let interval: TimeInterval | |
let action: (T) -> Void | |
private var _lastDispatchTime: DispatchTime? | |
public init(_ dispatchQueue: DispatchQueue, interval: TimeInterval, action: @escaping (T) -> Void) { | |
self.dispatchQueue = dispatchQueue | |
self.interval = interval | |
self.action = action | |
} | |
/// Request action to execute. | |
public func requestAction(_ dependency: T) { | |
let dispatchTime: DispatchTime = .now() + interval | |
_lastDispatchTime = dispatchTime | |
dispatchQueue.asyncAfter(deadline: dispatchTime) { | |
guard self._lastDispatchTime == dispatchTime else { | |
// ignore if requested again during interval. | |
return | |
} | |
self.action(dependency) | |
} | |
} | |
} | |
extension Debouncer where T == Void { | |
public func requestAction() { | |
requestAction(()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment