我正在为一项超级简单的交易而苦苦挣扎。它总是失败并显示消息“事务所有重试均失败”,但除此之外没有任何错误消息logcat
.
当我调试它时,我发现它被重试了几次。我真的不知道为什么,因为其他交易运行没有问题。
我只想将一个文档从一个集合克隆到另一个集合中。思考从“videos
" to "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());
}
});
}
根据有关交易的文档 https://firebase.google.com/docs/firestore/manage-data/transactions:
如果事务读取文档并且另一个客户端修改任何
对于这些文档,Cloud Firestore 会重试事务。此功能
确保事务在最新且一致的数据上运行。
因此,如果在交易完成之前源文档已被修改,您可以预期您的交易将被重试。
您还可以预期交易可能会失败。
交易可能因以下原因失败:
- 该事务包含写操作之后的读操作。读操作必须始终在任何写操作之前进行。
- 事务读取在事务外部修改的文档。在这种情况下,事务会自动再次运行。
事务重试有限次数。
失败的事务返回错误并且不会写入任何内容
数据库。您不需要回滚事务;云
Firestore 会自动执行此操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)