Firestore如何停止交易? [英] Firestore how stop Transaction?

查看:52
本文介绍了Firestore如何停止交易?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在事务中,我只想在不存在数据的情况下写数据

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;

 });

您可以在我的文档参考中看到基于uid,并且在我的日志中我正在打印uid

You can see in my Document reference is uid based and in my log I am printing uid

因此,在不存在uid数据的情况下,我的日志仅打印一次,而我在其他地方调用transaction.set(),它继续显示uid日志,其中已经存在数据,如果不调用transaction.set( )

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()

如何阻止它.

推荐答案

文档中提供了一个示例,只是抛出一个异常,它将退出事务并停止执行.

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

这篇关于Firestore如何停止交易?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆