Created
October 7, 2020 08:53
-
-
Save pulsar256/1e9490b1864688a75d7fda449e73ea68 to your computer and use it in GitHub Desktop.
throttled_iterator.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension on Iterator { | |
void throttledForEach(int parallelFutures, ForEachCallback onData, | |
[ItemProcessedCallback onProgress]) async { | |
final semaphores = StreamController<int>(); | |
while (parallelFutures-- > 0) { | |
semaphores.add(1); | |
} | |
await for (var _ in semaphores.stream) { | |
if (!moveNext()) break; | |
var f = onData(current) | |
..then((value) => semaphores.add(1)) | |
..catchError((e) { | |
semaphores.add(1); | |
throw e; | |
}); | |
if (onProgress != null) { | |
f.then((value) => onProgress); | |
} | |
await f; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment