I use the following code to add userId to an array in a Cloud Firestore document:
DocumentReference reference = firebaseFirestore.collection("photos").document(photoId);
reference.update("views", FieldValue.arrayUnion(currentUser.getUid()))
.addOnSuccessListener(new OnSuccessListener<Void>()
{
@Override
public void onSuccess(Void aVoid)
{
reference.update("viewsCount", FieldValue.increment(1));
}
});
As you can see from the code, I want the viewsCount to increment only if element is added to the views array.
According to this Adding Data document, arrayUnion() adds elements to an array but only elements not already present, and thats exactly what I wanted.
But, the problem is that when I add an already present element into the array, the element is not inserted, but addOnSuccessListener is called, viewsCount is incremented and failureListener is never called. Is there any way to prevent this? I want the viewsCountto be incremented only when an element is inserted into views array.