2

I have two references I want to update:

1.

/items/item1/sumlikes: 4

"item1" is liked by 4 users. I need a transaction because multiple users can write this value at the same time: https://firebase.google.com/docs/database/android/read-and-write#save_data_as_transactions

2.

/users/myusername/item1: true

I add "item1" to the the username who liked it.

I would like to have the 1. and 2. writes atomic, so I need to use updateChildren with HashMap like in this example: https://firebase.google.com/docs/database/android/read-and-write#update_specific_fields

But how can I combine this with a transaction? Thank you for your help!

KENdi
  • 7,576
  • 2
  • 16
  • 31
Péter Aradi
  • 370
  • 1
  • 4
  • 12

1 Answers1

1

There is no way to run a transaction across multiple disparate locations. The only way to have a transaction covering both locations, is to run the transaction at a common node above both locations. That will severely reduce the scalability/concurrency of your database.

Also see:

One thing I investigated at some point is using security rules and regular writes (including multi-location updates like yours) to achieve the same result. It's definitely possible. But it quickly gets quite tricky. See my answer on Is the way the Firebase database quickstart handles counts secure?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you for your help! I enjoyed reading your post about how to solve this with validation rules :) I hope I understand it well: if something goes wrong because several users update the same node at the same time the validation can fail and I will get an error or Android. What is the best practice to handle this fails? Should I retry the update a few times? – Péter Aradi Jul 27 '17 at 09:27
  • 1
    Yup. In that case you'd indeed have your code retry. It is quite similar to how Firebase's transactions also work: when the server detects a conflict, it rejects the new value and the client retries. The main difference is that with Firebase's built-in transactions it is the SDK code that does the retry, while in my linked answer it is my custom code. – Frank van Puffelen Jul 27 '17 at 14:00