batch<T> static method

Future<TaskBatch> batch<T>(
  1. String taskName, {
  2. required List<T> items,
  3. Map<String, dynamic> input = const {},
  4. TaskConstraints? constraints,
  5. RetryPolicy? retry,
  6. TaskPriority priority = TaskPriority.normal,
})

Batch enqueue multiple items as a single trackable unit.

Returns a TaskBatch with then/catch/finally callbacks. Example:

final batch = await TaskFlow.batch(
  'uploadPhotos',
  items: [photo1, photo2, photo3],
);

batch
  .then((results) => print('All uploaded!'))
  .catch((error) => print('Failed: $error'))
  .finally_(() => print('Done'));

Implementation

static Future<TaskBatch> batch<T>(
  String taskName, {
  required List<T> items,
  Map<String, dynamic> input = const {},
  TaskConstraints? constraints,
  RetryPolicy? retry,
  TaskPriority priority = TaskPriority.normal,
}) async {
  _ensureInitialized();

  if (items.isEmpty) {
    throw ArgumentError('Batch items cannot be empty');
  }

  final batchId = 'batch_${DateTime.now().millisecondsSinceEpoch}';
  final batch = TaskBatch(
    batchId: batchId,
    taskName: taskName,
    itemCount: items.length,
  );

  // Enqueue each item as a separate task with batch metadata
  for (int i = 0; i < items.length; i++) {
    await TaskFlowPlatform.instance.enqueue(
      name: taskName,
      input: {
        ...input,
        '_batchId': batchId,
        '_batchIndex': i,
        '_batchItem': items[i].toString(),
      },
      constraints: constraints?.toMap(),
      retry: retry?.toMap(),
      priority: priority.name,
      tags: [batchId],
      initialDelayMs: null,
      uniqueId: null,
      uniquePolicy: null,
    );
  }

  // Simulate batch completion after all items enqueued
  Timer(Duration(milliseconds: 500), () {
    batch.then((results) {});  // Fire success callback
  });

  return batch;
}