When dealing with complex data that may be corrupted by simultaneous modifications, such as incremental counters, Firebase provides a transactional operation.
You pass this operation two arguments: an update function and an optional completion completion response. The update function takes the current state of the data as an argument and returns the new desired state that you want to write.
For example, if we wanted to increase the number of upvotes in a certain blog post, we would record the transaction as follows (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);
Source of obsolete
New source of firebase version
André kool
source share