Throttling and Debouncing in SwiftUI

Carmine Porricelli
3 min readApr 1, 2022

--

Throttling and debouncing are both techniques used to limit how many time a piece of code can execute. Generally they are used when an execution of code depends user interaction (typing, pressing buttons…).

Throttling

Throttling makes sure that an execution can’t run more than once in a given timespan.

Imagine you need to make a simple videogame with a spaceship, and you want it to just fire one missile per second... Throttling would come really in handy here! Just throttle for one second the code that makes the spaceship shoot and voilà.

Thanks to throttling the function is being called only once per second despite the user giving input much faster.

Debouncing

Debouncing makes sure that an execution runs only after the firing of that execution stops for a given time.

This technique has the most common use case when implementing a search field that uses an external APIs or that runs computational expensive functions to get the result. Debouncing can help performance and avoids useless APIs calls starting the search only when the user has stopped typing.

Thanks to the debouncing, the function is being called only after one second past the last user input.

Debouncing and Throttling in SwiftUI is EASY thanks to Apple’s built-in framework Combine.

Under the hood SwiftUI uses Combine and its Publishers in order to emit changes. Every time we use a Published decorator in an ObservableObject we are creating a publisher of that property and to access it we use the $ operator. SwiftUI’s Views can subscribe to any publisher thanks to the .onReceive modifier.

Publishers subscription che be debounced or throttled really easily thanks to their included methods.

That’s all you need to know for now. Here’s some code:

  1. Instantiation of the ObservableObject class containing our needed published methods.
  2. The .onReceive modifier takes a publisher as his first argument, we pass into it the userInput’s publisher accessing it trough the $ operator. Then we throttle the subscription for one second with the publisher’s method throttle.
  3. Here’s the throttled code given with a closure.

If you need to use debouncing the code remains almost unchanged, we just need to call the publisher’s method debounce instead of throttle. Really easy.

But how can we debounce/throttle something that does not depend on a published value change? It can be done, but it’s not as easy. I found this really well done code snippet online that abstracts the tricky part.

Commented on the bottom a few line on how to use it.

That’s all.

Here’s the repo with the demo code: https://github.com/Carminepo2/throttling-and-debouncing-in-swift-ui-demo.

--

--