A Dart utility package for easy async task cancellation

Overview

cancellation_token_hoc081098

Author: Petrus Nguyễn Thái Học

Dart CI Pub Pub codecov GitHub Style Hits

Dart Cancellation Token. Inspired by CancellationToken in C#. A Dart utility package for easy async task cancellation.

Features

  • Reuse a single CancellationToken for multiple tasks, and cancel all of them with a single call to CancellationToken.cancel().
  • Cancel futures and clean-up resources with token.guardFuture(block).
  • Cancel streams and clean-up resources with token.guardStream(stream)/Stream.guardedBy(token).
  • Integration with rxdart/rxdart_ext with useCancellationToken.
  • Very simple, lightweight, and easy to use.

Getting started

1. Add dependency

dependencies:
  cancellation_token_hoc081098: 

2. Import

import 'package:cancellation_token_hoc081098/cancellation_token_hoc081098.dart';

Usage

1. guardFuture

void main() async {
  // Create a CancellationToken
  final token = CancellationToken();

  // Simulate a long-running task
  Future<void> doWork(int number) async {
    print('doWork($number) started');
    await Future<void>.delayed(const Duration(milliseconds: 100));
    print('doWork($number) finished');
  }

  // Guard a Future
  final future = token.guardFuture(() async {
    for (var i = 0; i < 10; i++) {
      token.guard(); // Throws if token is cancelled
      await doWork(i);
      token.guard(); // Throws if token is cancelled
    }
    return 42;
  });

  future
      .then((v) => print('Result: $v'))
      .onError<Object>((e, st) => print('Error: $e'));

  // Cancel the token after 300ms
  await Future<void>.delayed(const Duration(milliseconds: 300));

  // Cancel the token
  token.cancel();

  // Wait a little longer to ensure that the Future is cancelled
  await Future<void>.delayed(const Duration(seconds: 2));

  // Output:
  // doWork(0) started
  // doWork(0) finished
  // doWork(1) started
  // doWork(1) finished
  // doWork(2) started
  // Error: CancellationException
  // doWork(2) finished
}

2. guardStream

void main() async {
  // Create a CancellationToken
  final token = CancellationToken();

  // Simulate a long-running task
  Future<void> doWork(int number) async {
    print('doWork($number) started');
    await Future<void>.delayed(const Duration(milliseconds: 100));
    print('doWork($number) finished');
  }

  // Guard a Stream
  final stream = Rx.fromCallable(() async {
    for (var i = 0; i < 10; i++) {
      token.guard(); // Throws if token is cancelled
      await doWork(i);
      token.guard(); // Throws if token is cancelled
    }
    return 42;
  }).guardedBy(token);

  stream
      .doOnData((v) => print('Result: $v'))
      .doOnError((e, st) => print('Error: $e'))
      .listen(null);

  // Cancel the token after 300ms
  await Future<void>.delayed(const Duration(milliseconds: 300));

  // Cancel the token
  token.cancel();

  // Wait a little longer to ensure that the stream is cancelled
  await Future<void>.delayed(const Duration(seconds: 2));

  // Output:
  // doWork(0) started
  // doWork(0) finished
  // doWork(1) started
  // doWork(1) finished
  // doWork(2) started
  // Error: CancellationException
  // doWork(2) finished
}

3. useCancellationToken

import 'package:rxdart_ext/rxdart_ext.dart';

void main() async {
  // Simulate a long-running task
  Future<void> doWork(int number) async {
    print('doWork($number) started');
    await Future<void>.delayed(const Duration(milliseconds: 100));
    print('doWork($number) finished');
  }

  // useCancellationToken
  final Single<int> single = useCancellationToken((cancelToken) async {
    for (var i = 0; i < 10; i++) {
      cancelToken.guard(); // Throws if token is cancelled
      await doWork(i);
      cancelToken.guard(); // Throws if token is cancelled
    }
    return 42;
  });

  final subscription = single
      .doOnData((v) => print('Result: $v'))
      .doOnError((e, st) => print('Error: $e'))
      .listen(null);

  // Cancel the subscription after 300ms
  await Future<void>.delayed(const Duration(milliseconds: 300));

  // Cancel the subscription
  await subscription.cancel();

  // Wait a little longer to ensure that the stream is cancelled
  await Future<void>.delayed(const Duration(seconds: 2));

  // Output:
  // doWork(0) started
  // doWork(0) finished
  // doWork(1) started
  // doWork(1) finished
  // doWork(2) started
  // doWork(2) finished
}

Features and bugs

Please file feature requests and bugs at the issue tracker.

License

MIT License

Copyright (c) 2022 Petrus Nguyễn Thái Học
You might also like...

Learn how to use Dart List Utility Methods in Flutter

Learn how to use Dart List Utility Methods in Flutter

Flutter Tutorial - List Utility Methods Learn how to use Dart List Utility Metho

Dec 29, 2021

A pure Dart utility library that checks for an internet connection by opening a socket to a list of specified addresses, each with individual port and timeout. Defaults are provided for convenience.

data_connection_checker A pure Dart utility library that checks for an internet connection by opening a socket to a list of specified addresses, each

Nov 29, 2022

Scaff is a simple command-line utility for generating Dart and Flutter components from template files.

Introduction Scaffold Generator for Dart and Flutter. scaff is a simple command-line utility for generating Dart and Flutter components from template

Jul 17, 2022

Interactive command line interface Couchbase Lite REPL utility built with the Dart

Interactive command line interface Couchbase Lite REPL utility built with the Dart

Couchbase Lite Dart CLI Interactive command line interface Couchbase Lite REPL utility built with the Dart programming language. This code uses the cb

Jul 20, 2022

Flutter package for displaying grid view of daily task like Github-Contributions.

Flutter package for displaying grid view of daily task like Github-Contributions.

flutter_annual_task flutter_annual_task Flutter package for displaying grid view of daily task like Github-Contributions. Example Usage Make sure to c

Sep 21, 2022

A simple package for working with multithreading, using an interface similar to Task in C#.

A simple package for working with multithreading, using an interface similar to Task in C#.

Oct 24, 2022

⚡ Cache Manager A tidy utility to handle cache of your flutter app like a Boss.

⚡ Cache Manager A tidy utility to handle cache of your flutter app like a Boss. It provides support for both iOS and Android platforms (offcourse). 🎖

Oct 25, 2022

Link-extractor - A Simple utility for extracting media urls from different websites

Link Extractor A Simple utility for extracting media urls from differennt social

Feb 5, 2022

📐 It's a set of common utility strategies to work with responsive styles with Flutter and CSS in JS

📐 It's a set of common utility strategies to work with responsive styles with Flutter and CSS in JS

@displaykit/responsive_styles You don't need to be worried just because you have to support multiple screens 📺 🖥 💻 📱 . It's a set of common utilit

Dec 16, 2022
Comments
Releases(1.0.0)
  • 1.0.0(Sep 18, 2022)

  • 1.0.0-beta.04(Sep 16, 2022)

    https://pub.dev/packages/cancellation_token_hoc081098/versions/1.0.0-beta.4

    • Refactor guardStream / guardedBy: pause and resume the returned StreamSubscription properly.

    Full Changelog: https://github.com/hoc081098/cancellation_token_hoc081098/compare/1.0.0-beta.03...1.0.0-beta.04

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0-beta.03(Sep 9, 2022)

    https://pub.dev/packages/cancellation_token_hoc081098/versions/1.0.0-beta.3

    • Override CancellationToken.toString() for better debugging.

    Full Changelog: https://github.com/hoc081098/cancellation_token_hoc081098/compare/1.0.0-beta.02...1.0.0-beta.03

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0-beta.02(Sep 6, 2022)

    https://pub.dev/packages/cancellation_token_hoc081098/versions/1.0.0-beta.2

    • Remove meta dependency.
    • Optimize CancellationToken implementation.

    Full Changelog: https://github.com/hoc081098/cancellation_token_hoc081098/compare/1.0.0-beta.01...1.0.0-beta.02

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0-beta.01(Sep 4, 2022)

Owner
Petrus Nguyễn Thái Học
Functional & Reactive Programming - Rx Fan 🌰 RxDart - RxKotlin - RxSwift - rxjs 🌸 Android - iOS - Flutter - Node.js - Angular
Petrus Nguyễn Thái Học
Dart package for Async Data Loading and Caching. Combine local (DB, cache) and network data simply and safely.

Stock is a dart package for loading data from both remote and local sources. It is inspired by the Store Kotlin library.

xmartlabs 59 Dec 24, 2022
A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

dio_http A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout

null 46 Dec 19, 2021
A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

Language: English | 中文简体 dio A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File

Flutter中国开源项目 11.2k Jan 3, 2023
Hive Wait provide a Hive repository to calling methods in the box as async.

Hive Wait provide a Hive repository to calling methods in the box as async.

Giáo Hồ 1 May 10, 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
Dusyeri provider task - Dusyeri provider task built using flutter

Düşyeri Provider Task https://github.com/alper-mf/dusyeri_provider_task/blob/7d1

null 1 May 9, 2022
Daily-Task-Manager a daily task manager application project created in flutter

This is a daily task manager application project created in flutter. Install this application on Android - Install from Play Store

DVS 0 May 10, 2022
A Dart package that constantly writes a string to an IOSink, simillarly to the UNIX yes utility.

yes A Dart package that constantly writes a string to an IOSink, simillarly to the UNIX yes utility. Usage // Write to stdout for 5 seconds. final con

null 0 Sep 22, 2022
A flutter package from AsurRaa for widgets and utility functions to support mobile departments here.

sura_flutter A flutter package from AsurRaa for custom widgets and utility functions. Migrate from 0.2.x to 0.3.x BREAKING CHANGE: remove FutureManage

AsurRaa 4 Nov 15, 2022
Screenshots - A command line utility and package for capturing screenshots for Flutter

A screenshot image with overlaid status bar placed in a device frame. For an example of images generated with Screenshots on a live app in both stores

Maurice McCabe 258 Nov 22, 2022