Firebase - Multiple users simultaneously updating same object using its old value

前端 未结 2 755
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 03:05

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

相关标签:
2条回答
  • 2020-12-11 03:20

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

    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.
        }
    });
    

    Legacy source

    New firebase version source

    0 讨论(0)
  • 2020-12-11 03:45

    Firebase database handles up to 100 simultaneous real time connections to your database if your are using their free plan but once the 101st users connects to your database the database would stop responding and would display the values that were last edited. Firebase is really good at handling real time connections simultaneously so it depends on your pricing plans. If you want to use the database for free, there will be no issues handling 100 connections but if you want to handle more users use their generous pricing plans.

    0 讨论(0)
提交回复
热议问题