Reputation: 13803
I am not sure how to use Firestore Increment in an atomic way. and I am little bit confused.
I have capacity
as field in my document. simultaneous users can increase or decrease the value of capacity
by updating the document. beside updating, in the same time, the user also needs to create some documents. previously I use transaction to ensure create and update operation will
so previously I use firestore transaction to ensure those operation either all of the operations succeed, or all of them failed.
but now I want to use Firebase Increment and batch operation like this
val batch = FirebaseFirestore.getInstance().batch()
// 1. set event data in liked events subcollection
val ref1 = FirestoreDocumentReference.user.getReference(user.uid).collection("likedEvents").document(likedEvent.eventID)
val savedData1 : HashMap<String,Any> = hashMapOf(
FIRESTORE_EVENT_FIELD_EVENT_ID to likedEvent.eventID,
FIRESTORE_EVENT_FIELD_TITLE to likedEvent.title,
FIRESTORE_EVENT_FIELD_VENUE to likedEvent.venue,
FIRESTORE_EVENT_FIELD_DATE_START_TIME to likedEvent.dateTimeStart,
FIRESTORE_EVENT_FIELD_THUMBNAIL_DOWNLOAD_PATH to likedEvent.thumbnailDownloadPath,
FIRESTORE_EVENT_FIELD_CREATED_AT to Calendar.getInstance().time
)
batch.set(ref1,savedData1)
// 2. update the rankPoint and capacity of event
val updateData : MutableMap<String,Any> = mutableMapOf(
FIRESTORE_EVENT_FIELD_RANKPOINT to FieldValue.increment(5),
FIRESTORE_EVENT_FIELD_CAPACITY to FieldValue.increment(-1)
)
val ref2 = FirestoreDocumentReference.event.getReference(likedEvent.eventID)
batch.update(ref2,updateData)
batch.commit().addOnSuccessListener {
completion(true,null)
}.addOnFailureListener { e ->
completion(false,e.localizedMessage)
}
if I do something like this, do I have the same result like updating capacity
using transaction ?
I have to ensure two things:
Upvotes: 0
Views: 194
Reputation: 598847
Batch write operations are executed transactionally on the server.
The difference between a batch write and a transaction, is that in a transaction you get the document data on the client first, before sending that data and the updated values to the server. In a batch write you simply send all the updates to the server, without first getting any value. Since FieldValue.increment()
allows changing a numeric field without the client first reading its value, this can be safely done in a batch operation.
So: yes, the updates will either all happen, or none of them will happen. And there is no chance of race conditions on the increments.
Upvotes: 1