0

In Firebase Realtime Database, let's say that I need to add a child_node1 to node1 and, immediately after that, a child_node2 to node2, the information being related.

I could easily add the second child node in the completion handler of the insertion of the first child node. But what if the user closes the app exactly during the second call? Or the network suddenly goes down?

How should I make sure that the information gets committed if and only if both calls (transactions) succeed?

For example, after creating a user in the main node (users), I want to also add him in another node called users-locations according to his location. What if an error occurs after adding in users but before finishing adding in users-locations?

Thanks!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Toma Radu-Petrescu
  • 2,152
  • 2
  • 23
  • 57
  • Have you read about transactions in Realtime Database? https://firebase.google.com/docs/database/ios/read-and-write#save_data_as_transactions – Doug Stevenson Feb 16 '18 at 22:51
  • @DougStevenson Yes, but as far as I understand, they are for the purpose of handling conccurent writes on the same data. In my case, I want to add the nodes in different locations. Could you please further explain me how I should use them to solve my problem? Thanks! – Toma Radu-Petrescu Feb 16 '18 at 22:59
  • 1
    Transactions will do both (you said "transaction", so I went there first). If you just want to write to two different locations at the same time, do a multi-location update. The blog is old, but the info is still relevant: https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html – Doug Stevenson Feb 16 '18 at 23:17
  • @DougStevenson The multi-location update is just what I need. Thanks! – Toma Radu-Petrescu Feb 17 '18 at 08:46

1 Answers1

2

What you're trying to do is a fan-out operation, and as Doug commented you'll typically want to do this with a single multi-location update. Multi-location updates scale much better than transactions.

For example, to write to both locations at once you'd do:

let updates = ["/node1/child_node1": "value", "/node2/child_node2": "value"]

ref.updateChildValues(updates)

Some great sources for reading more about these are:

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