A pure dart package to apply useful rate limiting strategies on regular functions.

Overview

Rate Limiter

Open Source Love License Dart CI CodeCov Version

[ Built with at Stream ]

Introduction

Rate limiting is a strategy for limiting an action. It puts a cap on how often someone can repeat an action within a certain timeframe. Using rate_limiter we made it easier than ever to apply these strategies on regular dart functions.

( Inspired from lodash )

Index

Installation

Add the following to your pubspec.yaml and replace [version] with the latest version:

dependencies:
  rate_limiter: ^[version]

Strategies

Debounce

A debounced function will ignore all calls to it until the calls have stopped for a specified time period. Only then it will call the original function. For instance, if we specify the time as two seconds, and the debounced function is called 10 times with an interval of one second between each call, the function will not call the original function until two seconds after the last (tenth) call.

Usage

It's fairly simple to create debounced function with rate_limiter

  1. Creating from scratch
final debouncedFunction = debounce((String value) {  
  print('Got value : $value');  
  return value;  
}, const Duration(seconds: 2));
  1. Converting an existing function into debounced function
String regularFunction(String value) {  
  print('Got value : $value');  
  return value;  
}  
  
final debouncedFunction = regularFunction.debounced(  
  const Duration(seconds: 2),  
);

Example

Often times, search boxes offer dropdowns that provide autocomplete options for the user’s current input. Sometimes the items suggested are fetched from the backend via API (for instance, on Google Maps). The autocomplete API gets called whenever the search query changes. Without debounce, an API call would be made for every letter you type, even if you’re typing very fast. Debouncing by one second will ensure that the autocomplete function does nothing until one second after the user is done typing.

final debouncedAutocompleteSearch = debounce(
  (String searchQuery) async {
    // fetches results from the api
    final results = await searchApi.get(searchQuery);
    // updates suggestion list
    updateSearchSuggestions(results);
  },
  const Duration(seconds: 1),
);

TextField(
  onChanged: (query) {
    debouncedAutocompleteSearch([query]);
  },
);

Throttle

To throttle a function means to ensure that the function is called at most once in a specified time period (for instance, once every 10 seconds). This means throttling will prevent a function from running if it has run “recently”. Throttling also ensures a function is run regularly at a fixed rate.

Usage

Creating throttled function is similar to debounce function

  1. Creating from scratch
final throttledFunction = throttle((String value) {  
  print('Got value : $value');  
  return value;  
}, const Duration(seconds: 2));
  1. Converting an existing function into throttled function
String regularFunction(String value) {  
  print('Got value : $value');  
  return value;  
}  
  
final throttledFunction = regularFunction.throttled(  
  const Duration(seconds: 2),  
);

Example

In action games, the user often performs a key action by pushing a button (example: shooting, punching). But, as any gamer knows, users often press the buttons much more than is necessary, probably due to the excitement and intensity of the action. So the user might hit “Punch” 10 times in 5 seconds, but the game character can only throw one punch in one second. In such a situation, it makes sense to throttle the action. In this case, throttling the “Punch” action to one second would ignore the second button press each second.

final throttledPerformPunch = throttle(
  () {
    print('Performed one punch to the opponent');
  },
  const Duration(seconds: 1),
);

RaisedButton(
  onPressed: (){
    throttledPerformPunch();
  }
  child: Text('Punch')
);

Pending

Used to check if the there are functions still remaining to get invoked.

final pending = debouncedFunction.isPending;
final pending = throttledFunction.isPending;

Flush

Used to immediately invoke all the remaining delayed functions.

final result = debouncedFunction.flush();
final result = throttledFunction.flush();

Cancellation

Used to cancel all the remaining delayed functions.

debouncedFunction.cancel();  
throttledFunction.cancel();
You might also like...

This package binds to Cronet's native API to expose them in Dart.

Experimental Cronet Dart bindings This package binds to Cronet's native API to expose them in Dart. This is an HTTP Client Package with almost the sam

Dec 9, 2022

Tiny Dart logging package

Tiny Dart logging package

Aug 3, 2022

The Dart code generator for your package versions. 🎯

The Dart code generator for your package versions. 🎯

The Dart code generator for your package versions. There is no way to get the package version from the code in the Dart ecosystem. Installation Add bu

Dec 14, 2022

Flutter_socks_proxy is a dart package, HTTP/Socks4/Socks5 proxy

flutter_socks_proxy flutter_socks_proxy is a dart package, HTTP/Socks4/Socks5 proxy Usage Use global import 'dart:convert';

Oct 23, 2022

Pub Release is a package to assist in publishing dart/flutter packages to pub.dev.

description Pub Release is a package that automates publishing dart/flutter packages to pub.dev. README Pub Release is a package that automates publis

Oct 13, 2022

A dart package to help you parse and evaluate infix mathematical expressions into their prefix and postfix notations.

A dart package to help you parse and evaluate infix mathematical expressions into their prefix and postfix notations.

Jan 28, 2022

This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON

This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON. Why? Compatible with all target plat

Jan 6, 2023

A dart package for decode and encode emv QR code

A dart package for decode and encode emv QR code

Nov 15, 2022

Dart package for random strings and numbers, with weights

randomness Dart package for random strings and numbers, with weights Random strings, numbers. RNG with weights. Cryptographically secure options. Gett

Aug 6, 2022
Comments
  • Add exponential backoff strategy

    Add exponential backoff strategy

    Very common strategy when you don't want the user to spam some action. Probably a first association when someon says rate limiting:

    https://en.wikipedia.org/wiki/Exponential_backoff#Rate_limiting

    Is it possible to implement this?

    opened by itsJoKr 1
Releases(1.0.0)
Owner
Stream
Build scalable newsfeeds, activity streams, chat and messaging in a few hours instead of weeks
Stream
FaaS (Function as a service) framework for writing portable Dart functions

Functions Framework for Dart This is a community-supported project, meaning there is no official level of support. The code is not covered by any SLA

Google Cloud Platform 485 Dec 26, 2022
Contains utility functions and classes in the style of dart:collection to make working with collections easier

The collection package for Dart contains a number of separate libraries with utility functions and classes that makes working with collections easier.

Dart 273 Dec 27, 2022
A pure Dart implementation of the Pusher Channels Client

pusher_channels is a pure Dart pusher channels client. This client is work in progress and it is unstable. Usage A simple usage example: import 'packa

Indaband 7 Nov 6, 2022
A Pure Dart Utility library that checks for an Active Internet connection

This Code comes from https://github.com/komapeb/data_connection_checker * ?? Internet Connection Checker A Pure Dart Utility library that checks for a

Rounak Tadvi 61 Nov 25, 2022
Extension functions on ValueListenable that allows you to work with them almost as if it was a synchronous stream.

functional_listener Extension functions on ValueListenable that allows you to work with them almost as if it was a synchronous stream. Each extension

null 54 Oct 9, 2022
A Dart package which supports checking if a current package is up-to-date.

pub_updater A Dart package which enables checking whether packages are up to date and supports updating them. Intended for use in CLIs for prompting u

Very Good Open Source 47 Oct 27, 2022
null 2 Apr 17, 2022
A Dart build script that downloads the Protobuf compiler and Dart plugin to streamline .proto to .dart compilation.

A Dart build script that downloads the Protobuf compiler and Dart plugin to streamline .proto to .dart compilation.

Julien Scholz 10 Oct 26, 2022
A package that lets you include a cool, nice looking and validated Password TextFormField in your app to enhance user experience. The package is fully & easily modifiable.

A package that lets you include a cool, nice looking and validated Password TextFormField in your app to enhance user experience. The package is fully

Muhammad Hamza 20 Jun 7, 2022
A Dart package to web scraping data from websites easily and faster using less code lines.

Chaleno A flutter package to webscraping data from websites This package contains a set of high-level functions that make it easy to webscrap websites

António Nicolau 30 Dec 29, 2022