Throttling calls in Swift
How to limit burst of calls and make your app happy again
Throttling wraps a block of code with throttling logic, guaranteeing that an action will never be called more than once each specified interval.
Throttle is typically used inside search boxes in order to limit the number of backend requests while user is typing for a query; without throttling when an user types fast, backend server may receive tons of non useful request which are quite costly.
Moreover client will be busy updating continuously the UI with no longer relevant results: the entire behaviour causes your app to look cheap and the logic unnecessary complex.
Usually when implementing this kind of feature the first options you may consider is to use an NSTimer fired/invalidated at your set interval. Repeating this boilerplate code in your view controller its not a good idea; usually you want to avoid any mess logic tracking state in a portion of your code that you’ve been trying to keep stateless.
Another solution involves RxSwift which has a throttle implementation out of the box; btw including an entire lib and use just a function its not a good practice after all.
The following implementation uses GCD to execute specified code to throttle wrapped inside a DispatchWorkItem .
The idea is to specify the maximum interval (in seconds) to execute the job; throttle function must be called at each change of the state (in our search box example you may want call it on textDidChange ); once called previous queued DispatchWorkItem is automatically cancelled and a new one is scheduled to get executed after your min interval.
Article continues on my blog; tap here to continue reading!