progressIterateCmd<T> function

StreamCmd<Msg> progressIterateCmd<T>({
  1. required int id,
  2. required Iterable<T> items,
  3. required Future<void> onItem(
    1. T item
    ),
})

Produces a UV-safe StreamCmd that runs onItem for each element and emits progress updates for a hosted ProgressBarModel.

The returned command emits:

Implementation

StreamCmd<Msg> progressIterateCmd<T>({
  required int id,
  required Iterable<T> items,
  required Future<void> Function(T item) onItem,
}) {
  final list = items.toList(growable: false);
  final total = list.length;

  Stream<Msg> stream() async* {
    yield ProgressBarSetMsg(id: id, current: 0, total: total);
    try {
      for (var i = 0; i < total; i++) {
        await onItem(list[i]);
        yield ProgressBarSetMsg(id: id, current: i + 1, total: total);
      }
      yield ProgressBarIterateDoneMsg(id: id);
    } catch (e, st) {
      yield ProgressBarIterateErrorMsg(id: id, error: e, stackTrace: st);
    }
  }

  return Cmd.listen<Msg>(stream(), onData: (m) => m);
}