There was a question about loading data from Firebase Firestore Cloud. There is a simple query:
val firestore = Firebase.firestore
suspend fun getDocuments(timestamp: Timestamp): List<Entity> =
firestore
.collection("collection")
.orderBy("modified_at", Query.Direction.ASCENDING)
.whereGreaterThan("modified_at", timestamp)
.get()
.await()
.toObjects(Entity::class.java)
What happens if something goes wrong while uploading documents? Will I receive incomplete data or an error?
In what order are the documents loaded? Does orderBy affect the load order?
CodePudding user response:
What happens if something goes wrong while uploading documents?
As far as I can see, you aren't uploading any documents, you're only reading them using get() which:
Executes the query and returns the results as a QuerySnapshot.
When it comes to performing CRUD operations in Firestore, there is always the possibility that an operation can fail, for example, due to improper security rules. That being said, it's always recommended to handle errors. So your method should contain a try-catch as sown below:
suspend fun getDocuments(timestamp: Timestamp): List<Entity> {
return try {
firestore
.collection("collection")
.orderBy("modified_at", Query.Direction.ASCENDING)
.whereGreaterThan("modified_at", timestamp)
.get()
.await()
.toObjects(Entity::class.java)
} catch (e: Exception) {
throw e
}
}
However, a more elegant solution would be to use a class that contains two fields, the data, and the exception. This practice is explained in the following resource:
In what order are the documents loaded?
You get the documents ordered according to what you pass as an argument to the orderBy()
method.
Does orderBy affect the load order?
For sure, that's why we are using it, to have a particular order.