Using Java - Firebase Admin SDK.
I have to make two updates on the Firebase Realtime Database. Update#1 has to happen and only then Update#2 should happen.
I was earlier using this :
ref.setValueAsync("update#1");
ref.setValueAsync("update#2");
But in very rare cases - update#2 was happening before update#1 - flow was breaking for our usecase; I refactored the code to this :
ref.setValue("update#1", null);
ref.setValueAsync("update#2");
This change was made with the assumption that setValue is a sync call and we will only go for update#2 once update#1 is done. But we have noticed that cases of update#2 happening before update#1 are still there - although very rare.
But in very rare cases - update#2 was happening before update#1
That's the expected behavior since the operations run in parallel. So there can be cases in which the second operation completes faster than the first one. So simply calling an operation right after the other doesn't offer you any guarantee of the order in which the operations will complete.
If you need to perform the second operation, only when you're 100% sure that the first operation is complete, then you have to pass to setValue()
method the actual data and a completion listener:
ref.setValue("data", new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError error, DatabaseReference dataRef) {
if (error != null) {
System.out.println("Failed because of " + error.getMessage());
} else {
//Perform the second operation.
}
}
})
So as soon as the first operation completes, inside the callback perform the second one.