A sophisticated tool for managing queues of asynchronous tasks, with a stream interface, strong typing and lots of helpful options.

Related tags

Templates dart queue
Overview

Secretary

A sophisticated task manager.

Secretary is a tool for keeping your futures in check. It's useful for managing queues of asynchronous tasks, where not all tasks should be executed simultaneously, or where some tasks might fail.

Features

  • Reliable task queue
  • Result validation
  • Retry handling: limits, policies, conditions
  • Type constraints for keys and results
  • Event stream, and convenience methods for splitting it into result and error streams
  • Concurrent tasks
  • Recurring tasks

Upcoming Features

  • Scheduled tasks (i.e. set a datetime for execution).
  • Better state tracking (stream updates with a more descriptive state of the Secretary, e.g. number of tasks running).
  • Event stream improvements, especially for incorporating recurring task events.

Simple use case

Imagine a situation where you want to manage the uploading of a number of files to some server, and you want to queue them so it doesn't all happen at once and kill whatever fragile networking protocol is the weakest link. You don't necessarily care about collecting any results from this process, but you do want to check if the HTTP status code was 200 (successful), and retry some number of times if it wasn't. You could do something like this:

Future<int> uploadFile(String path) async {
    // ... upload logic
    // maybe it returns 4xx or 5xx sometimes
    return 200;
}


final secretary = Secretary<String, int>(
    validator: (code) => code == 200 ? null : code, // returning null means no error, otherwise pass the code
    maxAttempts: 5, // retry up to 5 times
);

final paths = ['0001.mov', '0002.mov', '0003.mov']; // and so on and so on
for (String p in paths) {
    secretary.add(
        p,
        () => uploadFile(p),
    );
}

What about errors?

Let's say you have the above use case, but you want to make a record of files that fail to upload? Well you can simply add this line:

secretary.failureStream.listen((event) => recordFailure(event.key, event.error));

Note that there is also secretary.errorStream, but this also includes errors which resulted in a retry, alongside ones that resulted in failure. You can also sort these yourself if you want to log them by checking event.isFailure.

Also note that all SecretaryEvent objects, including successful ones, include a list of all errors they've encountered over all their attempts. In most cases, these will all be roughly the same as the final error, but you can access them with event.errors.

Retry conditions

Following on from the example above, what if you want to retry in general, but not for every error? For example, perhaps you get error 415 Unsupported Media Type when uploading a file. This is an error which won't change however many times you retry it, so there's no point. Simply add a retryIf condition:

final secretary = Secretary<String, int>(
    validator: (code) => code == 200 ? null : code,
    maxAttempts: 5,
    retryIf: (error) => error != 415,
);

In this case, tasks that result in a 415 error will be declared failures, and you'll be able to see their events in the stream and log them as above.

Waiting for results

If you want to get the value of a specific task asynchronously, you can use Secretary.waitForResult(key), for example:

Future<Result<Something, Error>> getValue(int thingId) async {
    if(results.containsKey(thingId)) {
        // Checking some local map of results first.
        return results[thingId];
    }
    // Tell the secretary to get the thing from some service.
    // Note that if the key is already in the task list, it won't be added again.
    secretary.add(thingId, () => thingService.getThing(thingId));
    final result = await secretary.waitForResult(thingId);
    // You could add [result] to [results] here, but it's better practice to use
    // secretary.listen when you create it instead.
    return result;
}
You might also like...

An asynchronous Kaboom wrapper, written in Dart.

Kaboom Dart An asynchronous Kaboom wrapper, written in Dart. Usage To get started, initialize a Kaboom instane: // Initializes a new Kaboom instance.

Apr 7, 2022

This is tool to create 3D Models which can be used in Flutter Applications. Tool is developed completely using Flutter.

three_d_model_tool A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you start

Nov 8, 2022

This package helps developer to sort the flutter/dart packages and plugins alphabetically, This makes it easier when managing too many packages and when working with teams

This package helps developer to sort the flutter/dart packages and plugins alphabetically, This makes it easier when managing too many packages and when working with teams

Package helps to sort the flutter/dart packages and plugins alphabetically, This makes it easier when managing too many packages and when working with

Dec 21, 2022

Fluro is a Flutter routing library that adds flexible routing options like wildcards, named parameters and clear route definitions.

Fluro is a Flutter routing library that adds flexible routing options like wildcards, named parameters and clear route definitions.

English | Português The brightest, hippest, coolest router for Flutter. Features Simple route navigation Function handlers (map to a function instead

Jan 4, 2023

Tic Tac Toe game with single-player and multi-player options. Implemented minimax algorithm.

flutter_tic_tac_toe A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you star

Jan 1, 2022

This is a message/chat app with light and dark theme options

This is a message/chat app with light and dark theme options

this is a message/chat app #ui using #flutter that runs both Android and iOS devices also has a dark and light theme. We create in total 4 screens all

Dec 30, 2022

Flutterbodydetection - A flutter plugin that uses MLKit on iOS/Android platforms to enable body pose and mask detection using Pose Detection and Selfie Segmentation APIs for both static images and live camera stream.

Flutterbodydetection - A flutter plugin that uses MLKit on iOS/Android platforms to enable body pose and mask detection using Pose Detection and Selfie Segmentation APIs for both static images and live camera stream.

body_detection A flutter plugin that uses MLKit on iOS/Android platforms to enable body pose and mask detection using Pose Detection and Selfie Segmen

Dec 5, 2022

Money_manager - This app helps you with managing Income and Expense

Money_manager - This app helps you with managing Income and Expense

Expense App This app helps you with managing Income and Expense. It is coded in flutter, dart hive. TBH I want to code the same app in Flutter , React

Nov 14, 2022

WYSIWYG editor for Flutter with a rich set of supported formatting options. (WIP)

WYSIWYG editor for Flutter with a rich set of supported formatting options. (WIP)

✨ rich_editor WYSIWYG editor for Flutter with a rich set of supported formatting options. Based on https://github.com/dankito/RichTextEditor, but for

Dec 27, 2022
Comments
  • Concurrency support

    Concurrency support

    The goal is to allow concurrent execution of an arbitrary number of tasks simultaneously in a Secretary, which can be controlled by a concurrency parameter (or maxConcurrentTasks or something).

    enhancement 
    opened by alexobviously 0
Owner
Alex Baker
generative art and music, dartlang, flutter apps, chess stuff, etc
Alex Baker
Flutter Downloader - A plugin for creating and managing download tasks. Supports iOS and Android.

Flutter Downloader A plugin for creating and managing download tasks. Supports iOS and Android. This plugin is based on WorkManager in Android and NSU

Flutter Community 789 Jan 3, 2023
Type - Yet another typing test made in Flutter

another typing test Yet another typing test made in Flutter, because why not. Tr

Jeff Sieu 8 Jul 9, 2022
Wraps Flutter shared_preferences plugin, providing a iOS Suite Name support, it's helpful for sharing data from App to Widget.

shared_preferences_ios_sn Wraps Flutter shared_preferences plugin and provides an iOS Suite Name support, it's helpful for sharing data from App to iO

null 3 Sep 14, 2022
A collection of bricks that I find helpful.

A collection of bricks that I find helpful.

Elijah Luckey 11 Oct 24, 2022
This is a expenses app which keeps a track of the money spend. Mostly helpful for college students like me...

expenses_app A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

null 2 Jun 5, 2022
A new flutter package project which contains lots of beautiful alert dialog that will help you lot to create beautiful awesome alert box very quickly and easily.

A new flutter package project which contains lots of beautiful alert dialog that will help you lot to create beautiful awesome alert box very quickly and easily.

Karan Soni 8 Jan 8, 2022
Pokedex app built with Flutter (with lots of animations) using Clean Architecture.

Flutter Pokedex Pokedex app built with Flutter App preview Video demo Installation Add Flutter to your machine Open this project folder with Terminal/

null 8 Dec 29, 2022
Leverages libphonenumber to allow for asynchronous and synchronous formatting of phone numbers in Flutter apps

Leverages libphonenumber to allow for asynchronous and synchronous formatting of phone numbers in Flutter apps. Includes a TextInputFormatter to allow real-time AsYouType formatting.

Bottlepay 43 Nov 2, 2022
⚡FQuery is a powerful async state management solution for flutter. It caches, updates and fully manages asynchronous data in your flutter apps.

⚡ FQuery is a powerful async state management solution for flutter. It caches, updates and fully manages asynchronous data in your flutter apps. It ca

Piyush 21 Dec 22, 2022