runTransaction<T> method
- TransactionHandler<
T> transactionHandler, - {Duration timeout = const Duration(seconds: 30),
- int maxAttempts = 5}
Runs a transaction.
Parameters:
transactionHandler: The handler function for the transaction.timeout: Optional timeout duration.maxAttempts: Maximum retry attempts.
Returns: A Future with the transaction result.
Example:
await db.runTransaction((transaction) async {
// transaction operations
});
Implementation
Future<T> runTransaction<T>(
TransactionHandler<T> transactionHandler, {
Duration timeout = const Duration(seconds: 30),
int maxAttempts = 5,
}) async {
late T res;
String transName = generateRandomString(25);
Transaction trans = Transaction(name: transName);
dynamic tempRes;
bool success = false;
int retry = maxAttempts;
while (!success && retry > 0) {
try {
if (retry < maxAttempts) {
trans.__reset();
}
res = await transactionHandler(trans);
tempRes = await trans.__makeOperations();
success = true;
} catch (e) {
if (retry == 1) {
rethrow;
}
retry--;
success = false;
const int baseDelay = 50;
const int maxDelay = 10000;
final int delay = min(
baseDelay * (1 << (maxAttempts - retry)),
maxDelay,
);
final double jitter = Random().nextDouble() * delay * 0.5;
final int waitTime = (delay + jitter).round();
await Future.delayed(Duration(milliseconds: waitTime));
}
}
if (res != null) {
return res;
}
return tempRes;
}