batch<T> method

T batch<T>(
  1. 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

T batch<T>(T Function() callback) {
  if (_isBatchRunning) {
    return callback();
  }

  try {
    _isBatchRunning = true;
    return callback();
  } finally {
    _isBatchRunning = false;
    _endBatch();
  }
}