Firebase数据库递增一个int [英] Firebase database increment an int
问题描述
要在数据库中递增一个int值,我首先使用侦听器获取该值,将其递增1,然后将新值设置为数据库.这可行,但是我想知道是否有更简单的方法可以做到这一点.这样看来工作量太大.
For incrementing an int value in my database , I first get that value by using a listener , increment it by 1 and then set the new value to database. This works but I want to know if there is an easier way of doing this. This way seems like too much work.
推荐答案
Firebase数据库中没有服务器端增加值(或执行其他计算)的方法.
There is no server-side way to increment values (or do other calculations) in the Firebase Database.
您的方法是做到这一点的一种方法,但它有可能导致比赛状态.
Your approach is one way of doing this, but it has the chance of leading to a race condition.
- 数据库中的值为12
- 客户端1读取值12
- 客户端2读取值12
- 客户端1写入其增量值13
- 客户端2写入其增量值13
现在结果可能不正确(取决于您的用例).
The result is now likely incorrect (it depends on your use-case).
在这种情况下,使其工作的一种方法是使用Firebase事务,该事务将读取和写入结合为一个功能.
In that case, one way to make it work is to use Firebase transactions, which combine the reading and writing into a single function.
Firebase数据库文档中介绍了交易. .我强烈建议您阅读.在那儿花几个小时可以避免很多问题.从文档中:
Transactions are covered in the Firebase Database documentation. I highly recommend reading it. A few hours spent there will prevent many problems down the road. From the docs:
postRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Long value = mutableData.getValue(Long.class);
if (value == null) {
mutableData.setValue(0);
}
else {
mutableData.setValue(value + 1);
}
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
Log.d(TAG, "transaction:onComplete:" + databaseError);
}
});
这篇关于Firebase数据库递增一个int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!