【问题标题】:Cannot find .runtransaction() equivalent for Firebase Cloud Firestore找不到与 Firebase Cloud Firestore 等效的 .runtransaction()
【发布时间】:2018-04-19 07:22:03
【问题描述】:

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

【问题讨论】:

标签: java android firebase google-cloud-firestore


【解决方案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;
        }
    });
}

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 2018-06-06
    • 2019-07-23
    • 2023-03-17
    • 2019-10-10
    • 2021-06-19
    • 2019-04-12
    • 2019-01-16
    • 2019-08-07
    相关资源
    最近更新 更多