无法找到与Firebase Cloud Firestore等效的.runtransaction()

时间:2017-11-07 01:40:46

标签: java android firebase google-cloud-firestore

当我预期用户会同时写入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中找到相应的,我无法在文档中找到。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

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;
        }
    });
}