batch<T> static method

FutureOr<T> batch<T>(
  1. FutureOr<T> fn(), {
  2. String? label,
})

Runs fn inside a global batch.

Any store mutated while the batch is open has its notifyListeners() deferred. Once the outermost global batch closes, all affected stores are deduped and flushed exactly once.

Implementation

static FutureOr<T> batch<T>(
  FutureOr<T> Function() fn, {
  String? label,
}) {
  final effectiveLabel = label ?? 'Orbit.batch';
  _openGlobalBatch(effectiveLabel);
  _openUndoBatch(effectiveLabel);

  try {
    final result = fn();
    if (result is Future) {
      return (result as Future).whenComplete(() {
        _closeUndoBatch();
        _closeGlobalBatch();
      }) as FutureOr<T>;
    }
    _closeUndoBatch();
    _closeGlobalBatch();
    return result;
  } catch (error) {
    _closeUndoBatch();
    _closeGlobalBatch();
    rethrow;
  }
}