runBatch<T, R> static method
Runs a batch of operations in an isolate.
The function parameter is the function to run for each item in the batch.
The items parameter is the list of items to process.
The batchSize parameter determines how many items to process in each isolate.
Returns a list of results, one for each input item.
Implementation
static Future<List<R>> runBatch<T, R>({
required R Function(T) function,
required List<T> items,
int batchSize = 50,
}) async {
if (items.isEmpty) {
return [];
}
if (items.length <= batchSize) {
// For small batches, run in a single isolate
return Isolate.run(() => items.map(function).toList());
}
// For larger batches, split into multiple isolates
final results = <R>[];
final batches = <List<T>>[];
// Split items into batches
for (var i = 0; i < items.length; i += batchSize) {
final end = (i + batchSize < items.length) ? i + batchSize : items.length;
batches.add(items.sublist(i, end));
}
_log.fine('Processing ${items.length} items in ${batches.length} batches');
// Process each batch in a separate isolate
final futures = batches.map((batch) {
return Isolate.run(() => batch.map(function).toList());
});
// Collect results
final batchResults = await Future.wait(futures);
for (final batchResult in batchResults) {
results.addAll(batchResult);
}
return results;
}