Reputation: 2396
How can I add to a list in a Firebase Realtime Database transaction using MutableData?
In a normal non-transaction type update, I can simply use
DatabaseReference refDatabase = ...
refDatabase.push().setValue(value);
But with MutableData, no such push() method exists. How to add to a list and get a unique key?
I'm looking for something like
public Transaction.Result doTransaction(MutableData mutableData) {
mutableData.push().setValue(value);
...
but this does not exist.
Upvotes: 0
Views: 614
Reputation: 38299
I think I understand the point of your question and comment: It would be nice to know if the absence of push()
was an oversight by the API designers, or it was intentionally omitted to prevent users from doing something that was unsafe or otherwise "bad".
There is a workaround, right? You know the reference the transaction is run on. The mutable data is the value of that reference location. Can't you just make the reference variable a package field, or a final
class variable, and use it in the callback to call push()
? It's ugly, but I think should work.
I'll also take a guess that push()
was omitted from MutableData
for a reason. The documentation for doTransaction() states:
This method will be called, possibly multiple times, with the current data at this location. It is responsible for inspecting that data and returning a Transaction.Result specifying either the desired new data at the location or that the transaction should be aborted.
Since this method may be called repeatedly for the same transaction, be extremely careful of any side effects that may be triggered by this method.
Maybe generating keys and adding elements to a list is not something you want to be doing, since it may occur multiple times.
Upvotes: 1