withTransaction method Null safety
- Future<
bool> callback(- StreamQueue<
T>
- StreamQueue<
Passes a copy of this queue to callback
, and updates this queue to match
the copy's position if callback
returns true
.
This queue won't emit any events until callback
returns. If it returns
false
, this queue continues as though withTransaction hadn't been
called. If it throws an error, this updates this queue to match the copy's
position and throws the error from the returned Future
.
Returns the same value as callback
.
See also startTransaction and cancelable.
/// Consumes all empty lines from the beginning of [lines].
Future<void> consumeEmptyLines(StreamQueue<String> lines) async {
while (await lines.hasNext) {
// Consume a line if it's empty, otherwise return.
if (!await lines.withTransaction(
(queue) async => (await queue.next).isEmpty)) {
return;
}
}
}
Implementation
Future<bool> withTransaction(
Future<bool> Function(StreamQueue<T>) callback) async {
var transaction = startTransaction();
var queue = transaction.newQueue();
bool result;
try {
result = await callback(queue);
} catch (_) {
transaction.commit(queue);
rethrow;
}
if (result) {
transaction.commit(queue);
} else {
transaction.reject();
}
return result;
}