In transaction I only want to write data if data not present
DocumentReference callConnectionRef1 = firestore.collection("connectedCalls").document(callChannelModel.getUid());
firestore.runTransaction(new Transaction.Function < Void > () {
@Override
public Void apply(Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(callConnectionRef1);
Log.d(TAG, callChannelModel.getUid());
if (!snapshot.exists()) {
//my code
transaction.set(callConnectionRef1, model);
} else {
//do nothing
}
return null;
});
You can see in my Document reference is uid based and in my log I am printing uid
So where uid's data not exist my Log prints only once and I call transaction.set() elsewhere it keep showing Log of uid where data exists already it looks like my transaction keep running if I don't call transaction.set()
How can I stop it.
It happened to me too on Android. The transaction performs 5 attempts to apply itself, and only then the onFailure()
function is called (even if you throw an exception in the apply()
function).
But looks like this is the expected behavior:
MAX_ATTEMPTS
defaults to 5.There is an example given in the documentation, just throw an exception and it will exit the transaction and stop executing.
db.runTransaction(new Transaction.Function<Double>() {
@Override
public Double apply(Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(sfDocRef);
double newPopulation = snapshot.getDouble("population") + 1;
if (newPopulation <= 1000000) {
transaction.update(sfDocRef, "population", newPopulation);
return newPopulation;
} else {
throw new FirebaseFirestoreException("Population too high",
FirebaseFirestoreException.Code.ABORTED);
}
}
}).addOnSuccessListener(new OnSuccessListener<Double>() {
@Override
public void onSuccess(Double result) {
Log.d(TAG, "Transaction success: " + result);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Transaction failure.", e);
}
});
DocSnippets.java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With