cancelPrevious<T> function

Future<T> Function() cancelPrevious<T>(
  1. Future<T> fn()
)

Returns a wrapper that cancels previous in-flight calls when invoked again; the superseded future throws CancelPreviousException. Roadmap #183.

Implementation

Future<T> Function() cancelPrevious<T>(Future<T> Function() fn) {
  int generation = 0;
  return () async {
    final int myGen = ++generation;
    final T result = await fn();
    if (myGen != generation) throw CancelPreviousException();
    return result;
  };
}