I have an Android app and I need make Firestore subscription to get docs created during the last hour. I have created-timestamp field in all docs. So the subscription should work like this: if docs stops to be created, over the time result bundle should contains less and less docs (filtering only the last hour relatively current time). What is the best way to do this? Thanks.
2
Answers
You cannot use the
onSnapshot()
method to listen to the collection because the docs in your collections do not change: After receiving the initial query snapshot the snapshot handler will not receive any new snapshot (unless another change occurs in one of the documents of course)One solution is to fetch the collection every minute. This can be costly.
Another approach would be to use a Cloud Function to update a specific flag in the docs one hour after creation and use
onSnapshot()
because in this case the documents do get updated!There is no way to make the timestamp in the query dynamic, so you will have to remove the expired documents from the results in your application code.
This takes two steps:
The query itself should be quite simple: calculate the timestamp of one hour ago, and add a realtime listener on documents with a creation timestamp greater or equal to that.
When you start the query this will give you the correct documents, and it will give you the new documents. But since the timestamp in the query is fixed, it won’t remove the outdated documents.
Then you’ll have to run a local process periodically (say every few seconds or so) to check for expired documents in the results you got last.
Also see: