Created
June 16, 2020 10:27
-
-
Save alemar11/c16779848f5040de99da41e92994389b to your computer and use it in GitHub Desktop.
TypingThrottler
This file contains hidden or 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 | |
final class TypingThrottler { | |
typealias Handler = (String) -> Void | |
let interval: TimeInterval | |
let handler: Handler | |
private var workItem: DispatchWorkItem? | |
// handler will be called after the user has stopped typing for the given `interval` (seconds) | |
init(interval: TimeInterval = 0.4, handler: @escaping Handler) { | |
self.interval = interval | |
self.handler = handler | |
} | |
// call this every time the text changes | |
func handleTyping(with text: String) { | |
workItem?.cancel() | |
workItem = DispatchWorkItem { [weak self] in | |
self?.handler(text) | |
} | |
if let workItem = self.workItem { | |
DispatchQueue.main.asyncAfter(deadline: .now() + interval, execute: workItem) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment