Created
April 11, 2016 09:07
-
-
Save koke/bba95f0d0a8706f973c2d0dc6208d25d 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
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