runTransaction<T> method
Executes updateFunction and then attempts to commit the changes applied
within the transaction. If any document read within the transaction has
changed, updateFunction is run again, up to maxAttempts times. After timeout (30 seconds by default) the
returned future fails with FirestoreErrorCode.deadlineExceeded and no new attempt starts; an attempt that
was committing may still take effect.
The transaction must read (with Transaction.get) before it writes.
With readOnly it is a read-only transaction
of the backend: all its reads, also of queries (Transaction.getQuery)
and aggregations (Transaction.getAggregate), see the database at one
point in time.
If this instance is terminated while the transaction runs, its next
read or its commit fails with FirestoreErrorCode.failedPrecondition
and it is not retried.
readTime (only with readOnly) reads the database as it was at that time.
Throws an ArgumentError if maxAttempts is less than 1 or readTime is
given without readOnly.
Implementation
Future<T> runTransaction<T>(
Future<T> Function(Transaction transaction) updateFunction, {
Duration timeout = const Duration(seconds: 30),
int maxAttempts = 5,
bool readOnly = false,
Timestamp? readTime,
}) async {
if (timeout <= Duration.zero) {
throw ArgumentError.value(timeout, 'timeout', 'must be positive');
}
bool timedOut = false;
final TransactionOptions options = TransactionOptions(
maxAttempts: maxAttempts,
readOnly: readOnly,
readTime: readTime,
);
_checkNotTerminated();
// Every request of the transaction is a call of its own (as in the JS
// SDK): a transaction does not hold off terminate().
final LiteTransactionClient client = LiteTransactionClient(this);
return TransactionRunner<T>(
createTransaction: () => core.Transaction(
client,
readOnly: options.readOnly,
readTime: options.readTime == null
? null
: SnapshotVersion(options.readTime!),
),
maxAttempts: options.maxAttempts,
// A scheduler of its own: a [TaskScheduler] holds only one pending
// task per [TaskId], and transactions run concurrently.
backoff: ExponentialBackoff(
TaskScheduler('transaction'),
TaskId.retryTransaction,
),
updateFunction: (core.Transaction transaction) {
if (timedOut) {
// No new attempt after the timeout; this error is not retried.
throw const TransactionTimedOut();
}
return updateFunction(Transaction(transaction, this));
},
isTerminated: () => _terminated,
).run().timeout(
timeout,
onTimeout: () {
timedOut = true;
throw FirestoreException(
errorCode: FirestoreErrorCode.deadlineExceeded,
message:
'The transaction did not complete within $timeout. An attempt that was committing may still take '
'effect.',
);
},
);
}