0

I am looking at this demo program for Firebase API for Flutter (dartlang) and after looking at the original source. I am not grokking the difference between runTransaction and set() and why the authors used one over the other.

Future<Null> _increment() async {
    // Increment counter in transaction.
    final TransactionResult transactionResult =
        await _counterRef.runTransaction((MutableData mutableData) async {
      mutableData.value = (mutableData.value ?? 0) + 1;
      return mutableData;
    });

    if (transactionResult.committed) {
      _messagesRef.push().set(<String, String>{
        _kTestKey: '$_kTestValue ${transactionResult.dataSnapshot.value}'
      });
    } else {
      print('Transaction not committed.');
      if (transactionResult.error != null) {
        print(transactionResult.error.message);
      }
    }
}

Per the comments in the source runTransaction is:

Performs an optimistic-concurrency transactional update to the data at this Firebase Database location.

And for set method the comments say:

The effect of the write will be visible immediately and the corresponding events will be triggered. Synchronization of the data to the Firebase Database servers will also be started.

Can someone ELI5 what is the difference and why the authors chose two different methods to write to the db?

The full demo code is here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Paul
  • 2,409
  • 2
  • 26
  • 29

2 Answers2

2

I can't tell you why the authors picked one over the other, but the difference between a transaction and a regular write is quite clear.

A regular write is precisely what the name implies: it writes the value to the location that you specify.

In the Firebase Database you use a transaction to write a new value to a location, based on the current value in that location. So it combines a read and a write operation. What's somewhat unusual about Firebase transactions is that they are compare-and-set operations.

For more details on what that means, I recommend reading these:

That link also shows how a transaction is different from reading and writing it yourself: a transaction will only perform the write operation if the current value was not modified since it was read.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

After reading through Frank's answer here is my understanding of why the author chose runTransaction() vs set().

So the ELI5 version is that, in this case, the runTransaction() is being used to update the database entry associated with _counterRef. We do an update to an existing entry, specifically, we update the integer value of the number of times a button is pushed.

The set() method is being used along with push() to add new entries to the database. That value is a key value string using the same value updated in the runTransaction() method, i.e. the values mutableData.value and transactionResult.dataSnapshot.value are the same.

Paul
  • 2,409
  • 2
  • 26
  • 29