tccpg288
tccpg288

Reputation: 3352

Cannot find .runtransaction() equivalent for Firebase Cloud Firestore

I had previously called the .runtransaction()method when I anticipated users would be simultaneously writing to a location in Firebase

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

        }
    });
}

I am trying to find the equivalent in the new Cloud Firestore API, I was unable to locate in the documentation. Any help is appreciated.

Upvotes: 1

Views: 778

Answers (1)

Jerin A Mathews
Jerin A Mathews

Reputation: 8712

Firestore have transactions for simultaneous database writes, The documentation is in here

Also here is a sample code

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

Upvotes: 1

Related Questions