Line data Source code
1 : import 'dart:async';
2 : import 'dart:math';
3 :
4 : /// A result emitted by [mapConcurrently], tagged with the index of its input.
5 : typedef ConcurrentResult<O> = ({int index, O? value});
6 :
7 : /// Runs [task] for every item while keeping at most [maxConcurrency] tasks in
8 : /// flight and emits each result as soon as it completes (completion order).
9 : ///
10 : /// [onCompleted] is called once per finished task with the total number of
11 : /// finished tasks, which makes it suitable for progress reporting.
12 6 : Stream<ConcurrentResult<O>> mapConcurrently<I, O>(
13 : List<I> items,
14 : Future<O?> Function(I item) task, {
15 : int maxConcurrency = 128,
16 : void Function(int completed)? onCompleted,
17 : }) {
18 : final StreamController<ConcurrentResult<O>> controller =
19 6 : StreamController<ConcurrentResult<O>>();
20 6 : if (items.isEmpty) {
21 1 : controller.close();
22 1 : return controller.stream;
23 : }
24 :
25 18 : final int limit = max(1, min(maxConcurrency, items.length));
26 : int nextIndex = 0;
27 : int active = 0;
28 : int completed = 0;
29 : bool cancelled = false;
30 :
31 12 : controller.onCancel = () {
32 : cancelled = true;
33 : };
34 :
35 6 : void pump() {
36 : if (cancelled) {
37 : return;
38 : }
39 18 : while (active < limit && nextIndex < items.length) {
40 6 : final int index = nextIndex++;
41 6 : active++;
42 30 : Future.sync(() => task(items[index])).then(
43 6 : (O? value) {
44 6 : active--;
45 6 : completed++;
46 5 : onCompleted?.call(completed);
47 6 : if (!cancelled && !controller.isClosed) {
48 6 : controller.add((index: index, value: value));
49 : }
50 6 : pump();
51 : },
52 1 : onError: (Object error, StackTrace stackTrace) {
53 1 : active--;
54 1 : completed++;
55 1 : onCompleted?.call(completed);
56 1 : if (!cancelled && !controller.isClosed) {
57 1 : controller.addError(error, stackTrace);
58 : }
59 1 : pump();
60 : },
61 : );
62 : }
63 24 : if (active == 0 && nextIndex >= items.length && !controller.isClosed) {
64 6 : controller.close();
65 : }
66 : }
67 :
68 6 : pump();
69 6 : return controller.stream;
70 : }
|