runTransaction method
- TransactionHandler handler, {
- bool applyLocally = true,
Atomically changes the data at this location with handler.
The handler's first run happens inside this call, on the value the client holds, so a set made right after this call comes after the transaction. Events and the Future
still wait for a later microtask. While the database is still opening its persistence, the first run
happens once it has opened. The handler returns a Transaction, never a Future: it cannot wait. It
may run again when the server's value differs (see TransactionHandler). With applyLocally each
run raises local events, which a later run or an abort may revert; with applyLocally false there
are no local events before the server answers.
A write the handler makes to this location, above or below it fails this transaction with
overridden-by-set. Other writes there (set, remove, setPriority, an update that writes
at, above or below this location, and the onDisconnect writes the client applies when the
connection drops) fail it with overridden-by-set at once while it waits for an earlier
transaction at, above or below it. Once its value is sent, it waits for the server's answer: it
commits when the server accepts the value, and fails with overridden-by-set when the server
answers that its data was stale. A transaction made while offline counts as sent.
Completes with committed true when the server took the value, or false when the handler
aborted. Fails with the handler's own error when it throws, max-retries when the handler has
run 25 times and the server still refuses the value, disconnected when the connection drops
after the value was sent, overridden-by-set when another write overrides it (see above), and
write-canceled after FirebaseDatabase.purgeOutstandingWrites. While offline the handler
runs on the local value (with applyLocally its result raises local events) and the Future
stays pending until the connection returns; there is no timeout. Transactions are kept in
memory only, also with persistence.
final TransactionResult r = await db.ref('seats/left').runTransaction((Object? v) {
// Nothing cached yet: commit null. When the server holds a value, this runs again with it.
if (v == null) {
return Transaction.success(null);
}
final int left = v as int;
return left == 0 ? Transaction.abort() : Transaction.success(left - 1);
});
Implementation
Future<TransactionResult> runTransaction(
TransactionHandler handler, {
bool applyLocally = true,
}) {
const String fnName = 'runTransaction';
final Path path = spec.path;
validateWritablePath(fnName, path);
validateNotReadOnlyKey(fnName, path);
// The handler's own error (or an invalid value it returned) fails the Future as it is; the
// transaction aborts.
Object? thrown;
StackTrace? thrownStackTrace;
TransactionOutcome update(Object? currentValue) {
try {
final Transaction result = handler(currentValue);
if (result.aborted) {
return TransactionOutcome.abort;
}
validateUserValue(fnName, result.value, path);
final Object? priority = result.priority;
if (priority != null) {
validateUserPriority(fnName, priority);
}
final Object? value = normalizeUserValue(result.value);
return CommitOutcome(
priority == null
? value
: <String, Object?>{
'.value': value,
'.priority': normalizeUserValue(priority),
},
);
} on Object catch (error, stackTrace) {
thrown = error;
thrownStackTrace = stackTrace;
return TransactionOutcome.abort;
}
}
return database.request<TransactionResult>((
Repo repo,
void Function(TransactionResult) complete,
void Function(Object, [StackTrace?]) fail,
) {
repo.startTransaction(
path,
update,
applyLocally: applyLocally,
onComplete:
(DatabaseError? error, Node? node, {required bool committed}) {
final Object? handlerError = thrown;
if (handlerError != null) {
fail(handlerError, thrownStackTrace);
} else if (error != null) {
fail(toApiError(error));
} else {
complete(
TransactionResult.internal(
committed: committed,
snapshot: DataSnapshot.internal(
this,
node ?? ChildrenNode.empty,
priorityIndex,
),
),
);
}
},
);
});
}