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