final DocumentReference docRef = db.collection("cities").document("SF");
ApiFuture<String> futureTransaction =
db.runTransaction(
transaction -> {
DocumentSnapshot snapshot = transaction.get(docRef).get();
Long newPopulation = snapshot.getLong("population") + 1;
// conditionally update based on current population
if (newPopulation <= 1000000L) {
transaction.update(docRef, "population", newPopulation);
return "Population increased to " + newPopulation;
} else {
throw new Exception("Sorry! Population is too big.");
}
});
// Print information retrieved from transaction
System.out.println(futureTransaction.get());
city_ref = firestore.doc "#{collection_path}/SF"
updated = firestore.transaction do |tx|
new_population = tx.get(city_ref).data[:population] + 1
if new_population < 1_000_000
tx.update city_ref, { population: new_population }
true
end
end
if updated
puts "Population updated!"
else
puts "Sorry! Population is too big."
end