The Firebase documentation states that transactions are used in scenarios where a field might be needed to update frequently(Like a counter,for example.) But I don't get the point, Why cant I just read the data from the database using a listener and write data to the node? I know it's very sketchy but I wanted to know what are the drawbacks of using this approach.Answer1:
Imagine a situation where two clients are both trying to update some count in the database at the same time. We'll call them Client A and Client B. Their behavior is ordered like this:<ol><li>Client A reads a count with value 1</li> <li>Client B reads a count with value 1</li> <li>Client A wants to increment the count. It writes a count of 1+1=2 back to the database.</li> <li>Client B wants to increment the count. It writes a count of 1+1=2 back to the database.</li> </ol>
In this situation, the count <em>should</em> be 3, but instead a value a of 2 remains in the database. The count is obviously wrong now, and a transaction would have prevented the problem by forcing the writes in a particular order, and forcing the second client to re-read the count after the first client updated it. This means one of the clients updates from 1 to 2, and the second client updates from 2 to 3. Using a transaction is the only way to ensure correctness in this situation.