Reputation: 3850
I am usingfirebase
to store my data.This is how my firebase database looks like.
In my code i am trying to generate a new unique appointment-id
on button click event. If the current appointment-id
is 88 then it should become 89 when the user presses the button on his app, and this appointment-id
is assigned to him as his unique appointment-id
. The problem that I am facing is that when two or more users press the button on their app at the same time, then the same appointment-id
is assigned to both of them.
I want my appointment-id
to be synchronized i.e only one user can access it at a time.Is this possible ? How can I achieve it? Thanks.
Upvotes: 2
Views: 1791
Reputation: 32604
Firebase has transactions that will help you with incremental counters.
Firebase apptRef = new Firebase("<my-firebase-app>");
apptRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData currentData) {
if(currentData.getValue() == null) {
currentData.setValue(1);
} else {
currentData.setValue((Long) currentData.getValue() + 1);
}
return Transaction.success(currentData); //we can also abort by calling Transaction.abort()
}
@Override
public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
//This method will be called once with the results of the transaction.
}
});
Read the Firebase docs for more information.
Upvotes: 4