gpt4 book ai didi

java - 非常简单的 Firestore 交易失败

转载 作者:搜寻专家 更新时间:2023-11-01 08:22:02 24 4
gpt4 key购买 nike

我正在为一项 super 简单的交易而苦苦挣扎。它总是失败并显示消息“事务失败所有重试”,但是 logcat 上没有错误消息。

当我调试它时,我看到它被重试了好几次。我真的不知道为什么,因为其他事务运行没有问题。

我只想将一个文档从一个集合克隆到另一个集合。从“videos”到“favorites”(我知道这可以在交易之外完成,正如@Alex 指出的那样,但这只是失败的部分,真正的交易时间更长)

private void copy(
final DocumentReference SOURCEDOCREF,
final CollectionReference TARGETCOLREF) {

Transaction.Function<? extends Void> transaction = new Transaction.Function<Void>() {

@Nullable
@Override
public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {

DocumentSnapshot doc = transaction.get(SOURCEDOCREF);
if (doc.exists()) {
DocumentReference favoriteRef = TARGETCOLREF.document("FV_" + doc.getId());
Map<String, Object> data = doc.getData();
transaction.set(favoriteRef, data);
return null;

// NOTE: This is reached, ie. the source doc exists
// the data recovered, and set into the transaction.
} else
throw new FirebaseFirestoreException("Item does not exist", FirebaseFirestoreException.Code.NOT_FOUND);
}
};

setMode(MODE_SPLASH);
FirebaseFirestore.getInstance().runTransaction(transaction)
.addOnSuccessListener(
(Activity) getContext(),
new OnSuccessListener<Object>() {
@Override
public void onSuccess(Object aVoid) {
setMode(MODE_FOLLOW);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
hide();
DialogHelper.customToast(getContext(), e.getMessage());
}
});
}

最佳答案

根据documentation about transactions :

If a transaction reads documents and another client modifies any of those documents, Cloud Firestore retries the transaction. This feature ensures that the transaction runs on up-to-date and consistent data.

因此,如果源文档在事务完成之前已被修改,您可以预期您的事务将被重试。

您也可以预期交易会失败。

A transaction can fail for the following reasons:

  • The transaction contains read operations after write operations. Read operations must always come before any write operations.
  • The transaction read a document that was modified outside of the transaction. In this case, the transaction automatically runs again. The transaction is retried a finite number of times.

A failed transaction returns an error and does not write anything to the database. You do not need to roll back the transaction; Cloud Firestore does this automatically.

关于java - 非常简单的 Firestore 交易失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50064746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com