void ReadDataEventsForLocalChanges()

in firestore/android/FirestoreSnippetsCpp/app/src/main/cpp/snippets.cpp [630:664]


void ReadDataEventsForLocalChanges(firebase::firestore::Firestore* db) {
  using firebase::firestore::DocumentReference;
  using firebase::firestore::DocumentSnapshot;
  using firebase::firestore::Error;
  using firebase::firestore::FieldValue;

  // Local writes in your app will invoke snapshot listeners immediately. This
  // is because of an important feature called "latency compensation." When you
  // perform a write, your listeners will be notified with the new data before
  // the data is sent to the backend.
  //
  // Retrieved documents have metadata().has_pending_writes() property that
  // indicates whether the document has local changes that haven't been written
  // to the backend yet. You can use this property to determine the source of
  // events received by your snapshot listener:

  // [START listen_document_local]
  DocumentReference doc_ref = db->Collection("cities").Document("SF");
  doc_ref.AddSnapshotListener([](const DocumentSnapshot& snapshot,
                                 Error error, const std::string& errorMsg) {
    if (error == Error::kErrorOk) {
      const char* source =
          snapshot.metadata().has_pending_writes() ? "Local" : "Server";
      if (snapshot.exists()) {
        std::cout << source << " data: " << snapshot.Get("name").string_value()
                  << std::endl;
      } else {
        std::cout << source << " data: null" << std::endl;
      }
    } else {
      std::cout << "Listen failed: " << error << std::endl;
    }
  });
  // [END listen_document_local]
}