runTransaction<T> method

Future<T> runTransaction<T>(
  1. TransactionHandler<T> transactionHandler,
  2. {Duration timeout = const Duration(seconds: 30),
  3. int maxAttempts = 5}
)

Executes the given TransactionHandler and then attempts to commit the changes applied within an atomic transaction.

In the TransactionHandler, a set of reads and writes can be performed atomically using the Transaction object passed to the TransactionHandler. After the TransactionHandler is run, FirebaseFirestore will attempt to apply the changes to the server. If any of the data read has been modified outside of this Transaction since being read, then the transaction will be retried by executing the provided TransactionHandler again. If the transaction still fails after 5 retries, then the transaction will fail.s

The TransactionHandler may be executed multiple times, it should be able to handle multiple executions.

Data accessed with the transaction will not reflect local changes that have not been committed. For this reason, it is required that all reads are performed before any writes. Transactions must be performed while online. Otherwise, reads will fail, and the final commit will fail.

By default transactions are limited to 30 seconds of execution time. This timeout can be adjusted by setting the timeout parameter.

By default transactions will retry 5 times. You can change the number of attemps with maxAttempts. Attempts should be at least 1.

Implementation

Future<T> runTransaction<T>(
  TransactionHandler<T> transactionHandler, {
  Duration timeout = const Duration(seconds: 30),
  int maxAttempts = 5,
}) async {
  late T output;
  await _delegate.runTransaction(
    (transaction) async {
      output = await transactionHandler(Transaction._(this, transaction));
    },
    timeout: timeout,
    maxAttempts: maxAttempts,
  );

  return output;
}