An easy way to throttle any function in Flutter.
So, what is Throttling?
In software, a throttling process, or a throttling controller as it is sometimes called, is a process responsible for regulating the rate at which application processing is conducted, either statically or dynamically. - Wikipedia
In scenarios where user interaction takes place there is one kind of problem that we often find ourselves battling with. The problem of a user interacting with our UI too quickly and us not being able to handle it.
Let’s conside an example. Suppose there’s a button which when tapped calls an API to fetch data. Now, a user may tap on the button repeatedly in a very short span of time. This will result in too many calls to the API. What’s worse is that these calls will take up all the available bandwidth or even in some cases the available memory which in turn could stall the user’s mobile device or browser.
The solution? To filter out the interactions based on time. Or in other words, only process one user interaction for a particular period of time and ignore the rest. That’s what throttling means for us in mobile or web development.
Let’s now see an easy way to do this in Dart & Flutter.
(This example uses RxDart and recommends some level of familiarity with RxDart or ReactiveX patterns)
• First we define a
throttle function returns a throttled version of the function we passed to it.
• And thats it. Let’s now use it.
As you can see, the throttled function
throttledOnClick is called thrice one after the other and “I’m throttled” is printed only once per 500 milliseconds signalling its correct behaviour.