gpt4 book ai didi

java - 找不到 Firebase Cloud Firestore 的 .runtransaction() 等效项

转载 作者:行者123 更新时间:2023-11-30 06:26:16 27 4
gpt4 key购买 nike

当我预计用户会同时写入 Firebase 中的某个位置时,我之前调用了 .runtransaction() 方法

 private void increasePollTotalVoteCounter(int checkedRadioButtonID) {
mSelectedPollRef.child("vote_count").runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
mutableData.setValue((Long) mutableData.getValue() + 1);
return Transaction.success(mutableData);
}

@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
if (databaseError != null){
Toast.makeText(getActivity().getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}

}
});
}

我试图在新的 Cloud Firestore API 中找到等效项,但无法在文档中找到。如有任何帮助,我们将不胜感激。

最佳答案

Firestore 具有用于同时数据库写入的事务,文档位于 here

这里还有一个示例代码

private Task<Void> addRating(final DocumentReference restaurantRef, 
final Rating rating) {
// Create reference for new rating, for use inside the transaction
final DocumentReference ratingRef = restaurantRef.collection("ratings")
.document();

// In a transaction, add the new rating and update the aggregate totals
return mFirestore.runTransaction(new Transaction.Function<Void>() {
@Override
public Void apply(Transaction transaction)
throws FirebaseFirestoreException {

Restaurant restaurant = transaction.get(restaurantRef)
.toObject(Restaurant.class);

// Compute new number of ratings
int newNumRatings = restaurant.getNumRatings() + 1;

// Compute new average rating
double oldRatingTotal = restaurant.getAvgRating() *
restaurant.getNumRatings();
double newAvgRating = (oldRatingTotal + rating.getRating()) /
newNumRatings;

// Set new restaurant info
restaurant.setNumRatings(newNumRatings);
restaurant.setAvgRating(newAvgRating);

// Commit to Firestore
transaction.set(restaurantRef, restaurant);
transaction.set(ratingRef, rating);

return null;
}
});
}

关于java - 找不到 Firebase Cloud Firestore 的 .runtransaction() 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47148650/

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