搜尋套件、儲存庫與 APP 分類

套件詳情v3.0.0

async_queue

此 Dart 套件確保您的非同步任務組依序執行,一個接一個。

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
8920
喜歡數
29
Pub 分數
150

安裝套件

flutter pub add async_queue

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

async_queue 套件確保一連串非同步任務依序執行,一個接一個地進行,維持順序並避免併發問題。它提供了一個簡單的佇列機制,用於以受控方式處理非同步作業,非常適合任務依賴性或執行順序至關重要的情境。此套件使用 Dart 建構,可無縫整合至所有主要平台的 Flutter 專案中。該套件輕巧且專注於可靠性,適用於背景處理、API 呼叫排序,或任何需要有序非同步執行的使用情境。

適用情境

  • 順序 API 呼叫
  • 後台任務處理
  • 依序操作
  • 帶有異步操作的狀態管理
  • 按順序加載資源

主要特色

  • 保證順序執行
  • 簡單的佇列介面
  • 跨平台支援
  • 輕量且依賴極少
  • 執行緒安全作業

適合對象

  • 需要有序異步執行的開發者
  • 具有依賴異步工作流程的應用程式
  • 需要可預測任務排程的專案
  • Flutter 應用針對多個平台
  • 重視程式碼簡潔性的團隊

使用建議

  • 不適用於平行任務執行
  • 每個實例限於單個佇列
  • 需要仔細管理佇列生命週期
  • 最適合小型到中型任務批次
  • 不處理重試邏輯或錯誤恢復

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

"Buy Me A Coffee"

Async Queue - ensure your list of async tasks execute in order

This dart package ensures your pack of async tasks executes in order, one after the other.

What's new in v3.0.0

  • addJob returns a Future — await individual job results directly, no more listener workarounds
  • Automatic retry on exceptions — jobs that throw are retried up to retryTime without manual retry() calls
  • onError callback — handle errors at the queue level: AsyncQueue(onError: (error, label) { ... })
  • Priority queue — addJob(..., priority: 10) to run important jobs first
  • Pause / Resume — pause() halts without losing jobs, resume() continues
  • Retry with delay — addJob(..., retryDelay: Duration(seconds: 2)) to wait between retries
  • Job timeout — addJob(..., timeout: Duration(seconds: 30)) to auto-fail slow jobs
  • State getters — isRunning, isPaused, isClosed

Features

  • (Normal Queue) Add multiple jobs into queue before firing
  • (Auto Queue) Firing job as soon as any job is added to the queue
  • (Both) Option to add queue listener that emits events that happen in the queue
  • Retry when a job failed with optional delay between retries
  • addJob returns a Future — await individual job results
  • Automatic retry on exceptions
  • onError callback for dedicated error handling
  • Priority-based job ordering
  • Pause / Resume without losing queued jobs
  • Per-job timeout
  • isRunning / isPaused / isClosed state getters

Installing and import the library:

Like any other package, add the library to your pubspec.yaml dependencies:

dependencies:
    async_queue: <latest_version>

Then import it wherever you want to use it:

import 'package:async_queue/async_queue.dart';

Usage

1. Normal Queue
 final asyncQ = AsyncQueue();
  asyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 1), () => print("normalQ: 1")));
  asyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 4), () => print("normalQ: 2")));
  asyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 2), () => print("normalQ: 3")));
  asyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 1), () => print("normalQ: 4")));

  await asyncQ.start();

    // normalQ: 1
    // normalQ: 2
    // normalQ: 3
    // normalQ: 4
2. Auto Start Queue
final autoAsyncQ = AsyncQueue.autoStart();

  autoAsyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 1), () => print("AutoQ: 1")));
  await Future.delayed(const Duration(seconds: 6));
  autoAsyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 0), () => print("AutoQ: 1.2")));
  autoAsyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 0), () => print("AutoQ: 1.3")));
  autoAsyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 4), () => print("AutoQ: 2")));
  autoAsyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 3), () => print("AutoQ: 2.2")));
  autoAsyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 2), () => print("AutoQ: 3")));
  autoAsyncQ.addJob((_) =>
      Future.delayed(const Duration(seconds: 1), () => print("AutoQ: 4")));

    // AutoQ: 1
    // AutoQ: 1.2
    // AutoQ: 1.3
    // AutoQ: 2
    // AutoQ: 2.2
    // AutoQ: 3
    // AutoQ: 4
Add Queue Listener
  final asyncQ = AsyncQueue();

  asyncQ.addQueueListener((event) => print("$event"));
Await job result (v3.0.0+)

addJob returns a Future that completes with the job's return value. This works alongside previousResult — they serve different purposes.

final q = AsyncQueue.autoStart();

// Each addJob returns a Future you can await for its result
final userFuture = q.addJob((_) async {
  return await api.getUser();  // returns "Sam"
});

// previousResult still chains between jobs
final postsFuture = q.addJob((previousResult) async {
  return await api.getPostsFor(previousResult);
});

final user = await userFuture;     // "Sam"
final posts = await postsFuture;   // [Post, Post, ...]
Automatic retry on exceptions (v3.0.0+)

Jobs that throw are automatically retried up to retryTime times. You no longer need to catch errors and call retry() manually (though you still can for custom logic).

q.addJob((_) async {
  // if this throws, it will be retried automatically
  return await api.fetchData();
}, retryTime: 3);
onError callback (v3.0.0+)

Handle errors at the queue level without parsing events:

final q = AsyncQueue(
  onError: (error, jobLabel) {
    print('Job $jobLabel failed: $error');
  },
);
Priority (v3.0.0+)

Higher priority jobs execute before lower priority ones. Default is 0. Same-priority jobs maintain FIFO order.

q.addJob((_) => lowPriorityTask(), priority: 1);
q.addJob((_) => highPriorityTask(), priority: 10);  // runs first
Pause / Resume (v3.0.0+)

Unlike stop() which destroys the queue, pause() preserves all queued jobs:

q.pause();   // current job finishes, no new jobs start
q.resume();  // picks up where it left off
Retry with delay (v3.0.0+)

Add a delay between retry attempts:

q.addJob((_) => callApi(), retryTime: 3, retryDelay: Duration(seconds: 2));
Job timeout (v3.0.0+)

Auto-fail a job if it exceeds a duration. Timed-out jobs trigger auto-retry like any other exception:

q.addJob((_) => slowTask(), timeout: Duration(seconds: 30));
Tell queue to retry a job
    q.addJob(() async {
      try {
        //do something
      } catch (e) {
        q.retry();
      }
    },
    //default is 1
     retryTime: 3,
    );
Flutter use cases:

This package would be useful if you have multiple widgets in a screen or even in multiple screens that need to do some async requests that are related to each other.

For examples:

  • To make one request from a widget wait for another request from another widget to finish.
  • To avoid multiple requests from the front end hitting the backend in a short time, which would confuse the backend.

Code example:

 @override
  Widget build(BuildContext context) {
    final aQ = AsyncQueue.autoStart();
    return Scaffold(
      body: Column(
        children: [
          TextButton(
            onPressed: () async {aQ.addJob((_) => Future.delayed(const Duration(seconds: 2), () => print("job1 ")));},
            child: const Text('job1'),
          ),
          TextButton(
            onPressed: () async {aQ.addJob((_) => Future.delayed(const Duration(seconds: 4), () => print("jobs2")));},
            child: const Text('job2'),
          ),
          TextButton(
            onPressed: () async {aQ.addJob((_) => Future.delayed(const Duration(seconds: 1), () => print("job3")));},
            child: const Text('job3'),
          ),
        ],
      ),
    );
  }

Appreciate Your Feedbacks and Contributes

If you find anything need to be improve or want to request a feature. Please go ahead and create an issue in the Github repo

所屬分類

原始碼儲存庫

使用此套件的專案

暫無相關資料。