큐 패키지는 다양한 소스에서 온 여러 비동기 작업(퓨처)을 유연하고 중앙 집중식으로 관리하고 기다릴 수 있게 해줍니다. 코드의 한 지점에서 퓨처를 대기열에 넣고 다른 곳에서 결과를 기다릴 수 있어 비동기 실행 흐름에 대한 제어가 향상됩니다. 배치 처리나 순차적 데이터 가져오기와 같은 조정된 비동기 작업이 필요한 시나리오에 적합합니다. 이 패키지는 가볍고 모든 주요 플랫폼과 호환되어 크로스플랫폼 애플리케이션에 적합합니다. 작업 생성과 결과 처리를 분리함으로써 코드의 가독성을 높입니다.
사용 사례
비동기 작업의 배치 처리
여러 API 호출 조정
비동기 작업의 지연 실행
UI 컴포넌트에서 비동기 워크플로우 관리
모듈 간 데이터 로딩 동기화
주요 기능
중앙화된 미래 대기열
어떤 위치에서나 미래를 기다리기
여러 비동기 소스를 지원합니다
크로스 플랫폼 호환성
최소한의 보일러플레이트
스레드 안전 작업
적합한 대상
복잡한 비동기 흐름을 관리하는 개발자
순서 있는 비동기 실행이 필요한 앱
반응형 또는 상태 관리 패턴을 사용하는 팀
다중 플랫폼을 대상으로 하는 프로젝트
고도의 비동기 복잡성을 가진 코드베이스
고려 사항
실시간 스트리밍을 위한 설계가 아님
큐 라이프사이클의 신중한 관리가 필요합니다
큰 큐를 사용할 경우 메모리 사용량이 증가할 수 있습니다
유한하고 예측 가능한 비동기 시퀀스에 가장 적합
내부적으로 재시도 로직 또는 오류 복구를 처리하지 않음
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
queue
Easily queue futures and await their values.
This library allows you to send a future to central queue. The queue will execute the futures in the order they are queued and once the future is complete it will return its result.
My use case was to rate limit calls to bluetooth devices. There were multiple bluetooth devices connected that may have different commands being sent from lots of areas in the app. The devices were tripping over themselves and not responding. A stream wasn't the appropriate tool as I needed to get the result back. Hence a library was born.
Alternative use cases could be spidering a website, downloading a number of files, or rate limiting calls to an API.
Usage
The most simple example:
import'package:queue/queue.dart';
main() async {
final queue = Queue();
//Queue up a future and await its resultfinal result = await queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
//Thats it!
}
A proof of concept:
import'package:queue/queue.dart';
main() async {
//Create the queue containerfinalQueue queue = Queue(delay: Duration(milliseconds: 10));
//Add items to the queue asyncroniously
queue.add(()=>Future.delayed(Duration(milliseconds: 100)));
queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
//Get a result from the future in line with awaitfinal result = await queue.add(() async {
awaitFuture.delayed(Duration(milliseconds: 1));
return"Future Complete";
});
//100, 10, 1 will reslove in that order.
result == "Future Complete"; //true
}
Parallel processing
This doesn't work in batches and will fire the next item as soon as as there is space in the queue
Use [Queue(delayed: ...)] to specify a delay before firing the next item
import'package:queue/queue.dart';
main() async {
final queue = Queue(parallel: 2);
//Queue up a future and await its resultfinal result1 = await queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
final result2 = await queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
//Thats it!
}
On complete
import'package:queue/queue.dart';
main() async {
final queue = Queue(parallel: 2);
//Queue up a couple of futures
queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
// Will only resolve when all the queue items have resolved.await queue.onComplete;
}
Rate limiting
You can specify a delay before the next item is fired as per the following example:
import'package:queue/queue.dart';
main() async {
final queue = Queue(delay: Duration(milliseconds: 500)); // Set the delay here//Queue up a future and await its resultfinal result1 = await queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
final result2 = await queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
//Thats it!
}
LIFO (Last In First Out)
You can configure the queue to process items in LIFO order (last in, first out) by setting the lifo parameter:
import'package:queue/queue.dart';
main() async {
// Create a LIFO queuefinal queue = Queue(lifo: true);
// Add items to the queue
queue.add(() => Future.delayed(Duration(milliseconds: 100))); // Will be processed last
queue.add(() => Future.delayed(Duration(milliseconds: 50))); // Will be processed second
queue.add(() => Future.delayed(Duration(milliseconds: 10))); // Will be processed first
}
Adding items to the front of the queue
You can add items to the front of the queue to process them sooner using the addToFront parameter:
import'package:queue/queue.dart';
main() async {
final queue = Queue();
// Add a regular item to the queue
queue.add(() => Future.delayed(Duration(milliseconds: 100)));
// Add an urgent item that should be processed next
queue.add(
() => Future.delayed(Duration(milliseconds: 50)),
addToFront: true
);
}
Cancel
If you need to stop a queue from processing call Queue.cancel();
This will cancel the remaining items in the queue by throwing a QueueCancelledException.
A cancelled queue is "dead" and should be recreated. If you try adding items to the queue after you
call cancel, it will throw a QueueCancelledException.
If you have no reason to listen to the results of the items, simply call dispose.
If you want to wait until all the items which are inflight complete, call Queue.onComplete first.
Disposing
If you need to dispose of the queue object (best practice in flutter any any time the queue object will close)
simply call queue.dispose();
This is necessary to close the Queue.remainingItems controller.
Reporting
If you want to query how many items are outstanding in the queue once, you can use the getter remainingItemCount.
import'package:queue/queue.dart';
final queue = Queue();
final count = queue.remainingItemCount;
If you want to get notified when the remainingItemCount changes, listen to the Queue.remainingItems stream.
import'package:queue/queue.dart';
final queue = Queue();
final remainingItemsStream = queue.remainingItems.listen((numberOfItems)=>print(numberOfItems));
//Queue up a couple of futures
queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
// Will only resolve when all the queue items have resolved.await queue.onComplete;
remainingItemsStream.close();
queue.dispose(); // Will clean up any resources in the queue if you are done with it.
Contributing
Pull requests are welcome. There is a shell script ci_checks.sh that will run the checks to get
past CI and also format the code before committing. If that all passes your PR will likely be accepted.