1

I was looking at the Firebase documentation and saw that you can increment a data in the database with the following line:

Database.database().reference().child("Post").setValue([
         "number" : ServerValue.increment(10)
])

It also says on the documentation that "the increment operation occurs directly on the database server", I don't really understand what that means. What is the difference between this operation and an operation like :

// We have previously retrieved the value of number which we have stored in a variable
Database.database().reference().child("Post").setValue([
         "number" : numberOldValue + 10
])

2 Answers2

3

Instead of you getting the value from the server and doing that little "atomic" action of adding a integer to another one the increment allows you to just say for what value you want to increment the one on the server. It works on the server side so you don't need to worry at all to get the current value. If it changes in a millisecond before you send your request it will notice that.

Extra info: It is also much faster than the transaction. Check it out here.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Tarik Huber
  • 7,061
  • 2
  • 12
  • 18
1

Transaction VS ServerValue

When working with data that could be corrupted by concurrent modifications, such as incremental counters, you can use a transaction operation,Using a transaction prevents current increment from being incorrect if multiple users star the same post at the same time or the client had stale data.

The benefit of ServerValue.increment(10) makes you no worry about grabbing the current value to increment it as it will get the current value and increment it with sent value automatically

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87