Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - Why check if DocumentSnapshot is not null AND call exists?

Take a look at this code example from the Firestore documentation:

DocumentReference docRef = db.collection("cities").document("SF");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document != null && document.exists()) {
                Log.d(TAG, "DocumentSnapshot data: " + document.getData());
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
           Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

https://firebase.google.com/docs/firestore/query-data/get-data

Why check if document != null? If I read the source code correctly (beginner), the exists method checks for nullity internally.

like image 266
Florian Walther Avatar asked Apr 07 '18 07:04

Florian Walther


1 Answers

A successfully completed task will never pass null for the DocumentSnapshot. If the requested document does not exist, you'll get an empty snapshot. This means that:

  • Calling document.exists() returns false
  • Calling document.getData() throws an exception

So there is indeed no reason to check if document != null before calling document.exists().

like image 145
Frank van Puffelen Avatar answered Oct 06 '22 02:10

Frank van Puffelen