transaction method

Future<Transaction> transaction(
  1. dynamic transactionUpdate(
    1. dynamic
    ), [
  2. bool applyLocally = true
])

Atomically updates data at actual database location.

This method is used to update the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.

The provided transactionUpdate function is used to update the current value into a new value.

DatabaseReference ref = firebase.database().ref('numbers');
ref.set(2);
ref.transaction((currentValue) => currentValue * 2);

var event = await ref.once('value');
print(event.snapshot.val()); //prints 4

The returned value from transactionUpdate function must be a Dart basic type or the error is thrown.

Set applyLocally to false to not see intermediate states.

Implementation

Future<Transaction> transaction(dynamic Function(dynamic) transactionUpdate,
    [bool applyLocally = true]) {
  final c = Completer<Transaction>();

  final transactionUpdateWrap =
      allowInterop((update) => jsify(transactionUpdate(dartify(update))));

  final onCompleteWrap = allowInterop(
    (error, bool committed, database_interop.DataSnapshotJsImpl snapshot) {
      if (error != null) {
        c.completeError(error);
      } else {
        c.complete(Transaction(
            committed: committed,
            snapshot: DataSnapshot.getInstance(snapshot)));
      }
    },
  );

  jsObject.transaction(transactionUpdateWrap, onCompleteWrap, applyLocally);
  return c.future;
}