batch<T> method

FutureOr<T> batch<T>(
  1. FutureOr<T> callback()
)
inherited

Executes the given callback function within a batch operation.

A batch operation allows multiple state changes to be grouped together, ensuring that any associated side effects are only triggered once, improving performance and reducing unnecessary re-renders.

The callback function should return a value of type T. The returned value will be the result of the batch operation.

Example usage:

final stateA = Signal(0);
final stateB = UseState(0);
final computed = UseCompute(
  () => stateA.value + stateB.value,
  [stateA, stateB],
);

Rt.batch(() {
  stateA.value = 1;
  stateB.value = 2;

  print(computed.value); // 0 -> because the batch operation is not completed yet.
});

print(computed.value); // 3 -> because the batch operation is completed.

Implementation

FutureOr<T> batch<T>(FutureOr<T> Function() callback) async {
  try {
    _batchRunningCount++;

    return callback is Future Function() ? await callback() : callback();
  } finally {
    _batchRunningCount--;

    if (_batchRunningCount == 0) {
      _endBatch();
    }
  }
}