问题描述
在查看原始资源之后,我正在看这个用于Flutter的Firebase API的演示程序(达特朗).我并没有想过 runTransaction
和 set()
之间的区别以及作者为什么一个使用另一个.
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);
}
}
}
每个源 runTransaction
中的注释为:
对于 set
方法,注释应为:
有人ELI5有什么区别吗?为什么作者选择两种不同的方法写入数据库?
Can someone ELI5 what is the difference and why the authors chose two different methods to write to the db?
完整的演示代码位于此处
推荐答案
我无法告诉您为什么作者选择了另一个,但是事务和常规写入之间的区别是很明显的.
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.
在Firebase数据库中,您可以使用事务根据该位置的当前值将新值写入该位置.因此,它结合了读取和写入操作.Firebase事务与众不同之处在于它们是比较设置操作.
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.
这篇关于runTransaction和set()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!