2

I have to update my code and implement another child update to a node by increasing its value by 1. My current code looks like this (which works fine):

String key = database.child("rides").push().getKey();

Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/rides/" + key, ride.toMap());
childUpdates.put("/ridesUser/" + ride.getUserID() + "/ownRides/" + key, ride.getTime());

database.updateChildren(childUpdates, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
    }
});

An easy way to add the increment code would be:

childUpdates.put("/stations/" + ride.getFromID() + "/rideCount", fromStation.getRideCount() + 1);

But fromStation.getRideCount() could already be outdated, if another user added a ride with this station. I've read several posts about incrementing values by using a transaction. How can I combine child updates and transactions? Should I run a transaction on "/stations/" + ride.getFromID() and do my children updates within the doTransaction() method? Is this atomically?

Chris
  • 4,255
  • 7
  • 42
  • 83

1 Answers1

3

If you've read several posts, you might have seen this already: it is not possible to combine multi-location updates and transactions.

Your options:

  1. do a transaction at the lowest common level in the tree

  2. use security rules to implement pseudo-transactions for your multi-location update. See this answer from Kato or this more recent answer from me

  3. write the "change record" from the client and then let a server (which is less likely to face contention) do the update transactionally. See for example my answer to this question: When should you use Firebase Transactions

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807