in firestore/android/FirestoreSnippetsCpp/app/src/main/cpp/snippets.cpp [342:377]
void AddDataTransactions(firebase::firestore::Firestore* db) {
using firebase::Future;
using firebase::firestore::DocumentReference;
using firebase::firestore::DocumentSnapshot;
using firebase::firestore::Error;
using firebase::firestore::FieldValue;
using firebase::firestore::Transaction;
// The following example shows how to create and run a transaction:
// [START simple_transaction]
DocumentReference sf_doc_ref = db->Collection("cities").Document("SF");
db->RunTransaction([sf_doc_ref](Transaction& transaction,
std::string& out_error_message) -> Error {
Error error = Error::kErrorOk;
DocumentSnapshot snapshot =
transaction.Get(sf_doc_ref, &error, &out_error_message);
// Note: this could be done without a transaction by updating the
// population using FieldValue::Increment().
std::int64_t new_population =
snapshot.Get("population").integer_value() + 1;
transaction.Update(
sf_doc_ref,
{{"population", FieldValue::Integer(new_population)}});
return Error::kErrorOk;
}).OnCompletion([](const Future<void>& future) {
if (future.error() == Error::kErrorOk) {
std::cout << "Transaction success!" << std::endl;
} else {
std::cout << "Transaction failure: " << future.error_message() << std::endl;
}
});
// [END simple_transaction]
}