Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class ViewController: UIViewController, UITextFieldDelegate {
private weak var tableView: UITableView!
private weak var textField: UITextField!
private lazy var throttle: Throttle<String> = Throttle(timeout: 0.3) { (query) in
self.runFetch(query)
}
private let switcher = SwitchToLatest()
private var results = [String]() {
didSet {
tableView.reloadData()
}
}
private var currentText = "" {
didSet {
if currentText.characters.count < 4 {
throttle.cancel()
}
else {
throttle.input(currentText)
}
}
}
override func viewDidLoad() {
textField.delegate = self
}
func textDidChange(sender: AnyObject) {
if currentText != textField.text {
currentText = textField.text!
}
}
private func runFetch(query: String) {
let fetcher = Fetcher(query: query) { result, error in
if let error = error {
//Handle it.
print("Error \(error)")
}
else if let result = result {
self.results = result.map { oneResult in return oneResult.text }
}
}
switcher.switchTo(fetcher)
}
@IBAction func refresh(sender: AnyObject) {
throttle.cancel()
runFetch(currentText)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.