Firebase - 多个用户同时使用其旧值更新同一对象 [英] Firebase - Multiple users simultaneously updating same object using its old value

查看:28
本文介绍了Firebase - 多个用户同时使用其旧值更新同一对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在跟踪用户通过 Android 应用更新 Firebase 数据库的计数.它现在的工作方式是,在交互时,用户的应用程序在数据库上查找当前计数(使用在新定义中定义的 addListenerForSingleValueEvent()ValueEventListener) 并向其添加一个,然后使用 mRef.setValue() 将计数设置为这个新值,其中 mRef 是对数据库.

I'm keeping track of a count that users update on the Firebase database through an Android app. The way it works right now is that upon interaction the user's app looks up the current count on the database (using a addListenerForSingleValueEvent() and onDataChange() method defined within the new ValueEventListener) and adds one to it and then sets the count to this new value using mRef.setValue() where mRef is the reference to the database.

我担心的问题是如果大量用户同时与数据库交互会发生什么;Firebase 是否负责确保正确读取和递增值,或者是否存在大量重叠并因此可能丢失数据.

The issue I'm worried about is what would happen if a large number of users interacted with the database together at the same time; does Firebase take care of making sure that the value is read and incremented properly or is there a lot of overlap and potentially a loss of data because of that.

推荐答案

当处理可能被并发修改损坏的复杂数据(例如增量计数器)时,Firebase 提供了事务操作.

When working with complex data that could be corrupted by concurrent modifications, such as incremental counters, Firebase provides a transaction operation.

你给这个操作两个参数:一个更新函数和一个可选的完成回调.update 函数将数据的当前状态作为参数,并将返回您想要写入的新的所需状态.

You give this operation two arguments: an update function and an optional completion callback. The update function takes the current state of the data as an argument and will return the new desired state you would like to write.

例如,如果我们想增加特定博客文章的点赞数,我们将编写如下交易(旧代码):

For example, if we wanted to increment the number of upvotes on a specific blog post, we would write a transaction like the following (Legacy code):

    Firebase upvotesRef = new Firebase("https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes");
upvotesRef.runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData currentData) {
        if(currentData.getValue() == null) {
            currentData.setValue(1);
        } else {
            currentData.setValue((Long) currentData.getValue() + 1);
        }
        return Transaction.success(currentData); //we can also abort by calling Transaction.abort()
    }
    @Override
    public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
        //This method will be called once with the results of the transaction.
    }
});

旧源

新的 firebase 版本源

这篇关于Firebase - 多个用户同时使用其旧值更新同一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆