withTransaction method

Future<bool> withTransaction (
  1. Future<bool> callback(
    1. StreamQueue<T>
    )
)

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 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) {
  var transaction = startTransaction();

  /// Avoid async/await to ensure that [startTransaction] is called
  /// synchronously and so ends up in the right place in the request queue.
  var queue = transaction.newQueue();
  return callback(queue).then((result) {
    if (result) {
      transaction.commit(queue);
    } else {
      transaction.reject();
    }
    return result;
  }, onError: (error) {
    transaction.commit(queue);
    throw error;
  });
}