RateLimit is great library from Sam Soffes. Its purpose is extremely simple, but powerful.
Let's dive in.
It's quite common to want to limit certain tasks by frequency. For instance, consider a feature that loads search suggestions as a user types characters into a text field. We'd probably want to throttle that to make sure we're not calling some HTTP API too often. Let's take a look at how to do this with RateLimit:
func updateSearchResultsForSearchController(searchController: UISearchController) {
RateLimit.execute(name: "search-suggestions", limit: 0.5) {
API.loadSearchSuggestions(searchController.searchBar.text)
}
}
We give our rate-limited task a name and a limit, then pass in a closure to be limited. Neat.
Sam offers another great example: Loading new data for a view controller inside viewDidAppear
. Imagine if that view controller lived inside a tab bar controller and the user decided to switch back and forth between tabs rapidly.
There'd be no reason to check for new data each time the view was shown, but we would like to check if enough time had passed since the last check.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
RateLimit.execute(name: "load-posts", limit: 60.0) {
API.loadNewPosts()
}
}
One last example: Performance. Imagine we were performing some complicated task in a loop, and wanted to update a UIProgressBar to reflect its progress.
We might not want to update the UIProgressBar every single iteration. To make our UI nice and responsive, we might limit the updates to only once every 500 milliseconds or so.
Note: By default RateLimit doesn't persist our limits across app launches. If we do need this behavior, we can just replace RateLimit
with PersistentRateLimit
.
More info about RateLimit can be found at git.io/ratelimit