printProgessAnimation<T> function

Future<T> printProgessAnimation<T>(
  1. FutureOrResultCallback<T> workload, {
  2. Duration animationSpeed = const Duration(milliseconds: 150),
  3. StringSink? output,
})

Write a progess animation to output while waiting for workload.

workload must not write to output, otherwise the animation will be interrupted.

output defaults to stdout.

Implementation

Future<T> printProgessAnimation<T>(
  FutureOrResultCallback<T> workload, {
  Duration animationSpeed = const Duration(milliseconds: 150),
  StringSink? output,
}) async {
  const positions = ["|", "/", "-", r"\", "|", "/", "-", r"\"];
  var idx = 0;

  // ignore: close_sinks
  final oSink = output ?? stdout;

  final timer = Timer.periodic(animationSpeed, (_) {
    oSink.write("${positions[idx]} \r");

    idx++;
    if (idx >= positions.length) {
      idx = 0;
    }
  });

  T res;
  try {
    res = await workload();
  } finally {
    timer.cancel();
  }

  return res;
}