패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.1.1

rate_limiter

일반 함수에 유용한 레이트 제한 전략을 적용하기 위한 순수한 Dart 패키지입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
15.1만
좋아요
102
Pub 점수
160

패키지 설치

flutter pub add rate_limiter

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

일반 함수에 효과적인 레이트 제한 전략을 구현하기 위해 설계된 순수 Dart 패키지입니다. 함수 실행의 빈도를 제어함으로써 시스템 과부하를 방지하며, API 호출, 검색 쿼리 및 기타 고주파 작업 관리에 이상적입니다. 단순성과 성능을 중심으로 개발되었으며, 다양한 레이트 제한 알고리즘을 지원하고 여러 플랫폼에서 원활하게 통합됩니다. 외부 종속성이 없이 스로틀링 또는 버스트 제어가 필요한 상황에서 특히 유용합니다.

사용 사례

  • API 요청 제한
  • 검색 입력 빈도 제한
  • 사용자 입력에서 스팸 방지
  • 돌발 워크로드 관리
  • 백그라운드 작업 실행 제어

주요 기능

  • 다양한 레이트 제한 전략을 지원합니다
  • 순수한 다트 구현
  • 크로스 플랫폼 호환성
  • 간단한 함수 래핑
  • 사용자 정의 가능한 제한 및 간격
  • 외부 종속성 없음

적합한 대상

  • 사용 제한이 있는 API를 개발하는 개발자
  • 입력 디바운싱이 필요한 앱
  • 부하 보호가 필요한 시스템
  • 고통화량을 가진 실시간 애플리케이션
  • 다중 플랫폼에서 Flutter를 사용하는 팀

고려 사항

  • 비동기 함수와 수동 통합이 필요합니다
  • 함수 수준의 속도 제한에 제한됨
  • 상태에 대한 내장된 지속성 없음
  • 경량 및 동기적 사용 사례에 가장 적합
  • 복잡한 동시성 패턴을 처리하기 위해 추가적인 조치가 필요할 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

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')
);
BackOff

BackOff is a strategy that allows you to retry a function call multiple times with a delay between each call. It is useful when you want to retry a function call multiple times in case of failure.

Usage

Creating backoff function is similar to debounce and throttle function.

  1. Creating from scratch
final response = backOff(
  // Make a GET request
  () => http.get('https://google.com').timeout(Duration(seconds: 5)),
  maxAttempts: 5,
  maxDelay: Duration(seconds: 5),
  // Retry on SocketException or TimeoutException
  retryIf: (e, _) => e is SocketException || e is TimeoutException,
);
  1. Converting an existing function into backoff function
Future<String> regularFunction() async {  
  // Make a GET request
  final response = await http.get('https://google.com').timeout(Duration(seconds: 5));
  return response.body;
}

final response = regularFunction.backOff(
  maxAttempts: 5,
  maxDelay: Duration(seconds: 5),
  // Retry on SocketException or TimeoutException
  retryIf: (e, _) => e is SocketException || e is TimeoutException,
);
Example

While making a network request, it is possible that the request fails due to network issues. In such cases, it is useful to retry the request multiple times with a delay between each call. This is where backoff strategy comes in handy.

final response = backOff(
  // Make a GET request
  () => http.get('https://google.com').timeout(Duration(seconds: 5)),
  maxAttempts: 5,
  maxDelay: Duration(seconds: 5),
  // Retry on SocketException or TimeoutException
  retryIf: (e, _) => e is SocketException || e is TimeoutException,
);
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();

카테고리

의존성

의존성 목록 1 개

소스 저장소

이 패키지를 사용하는 프로젝트

순위