Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore how stop Transaction?

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.

like image 674
Parvesh Monu Avatar asked Jun 07 '18 07:06

Parvesh Monu


2 Answers

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:

  1. See here: https://googleapis.dev/python/firestore/latest/transaction.html
    Notice MAX_ATTEMPTS defaults to 5.
  2. In this github issue https://github.com/firebase/firebase-js-sdk/issues/520 there's a request to add a "number of retries" option.
like image 63
Alaa M. Avatar answered Sep 30 '22 05:09

Alaa M.


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
like image 26
MobDev Avatar answered Sep 30 '22 04:09

MobDev