So i'm a bit new to firebase and i'm developing an android app. What I would like to do is this: I want to create a service that runs in the background that can listen to a whole collection in firestore (For example "messages"), and once a document is added to the collection I would like to check if the document contains a certain value, and if it does push a notification. An outline of the pseudocode:
messages.attachlistener(onNewDocument(doc) -> {
if(doc.getString(username) == my_username)
{
send_notification(doc.getString(message));
cache_message_for_later();
delete_doc_from_table();
}
};
My question is this: Is attaching a listener to a collection possible? I only found document listeners in the docs. If it is possible, would such a listener even be viable performance wise? (My thinking: this service would be running in the background at all times, but documents would get deleted after being cached so the table size wouldn't be too large and it might balance out?)
One of the best features of Cloud Firestore is real-time updates, that is the ability to push any data changes out to all apps. To “ listen ” for changes on a document or collection, we create a snapshot listener .
"The first query snapshot contains added events for all existing documents that match the query.", how to ignore the first snapshot and only listen for the actual added documents? @BlackCoffee You can't. You should instead figure out how to query for only the documents you want. Typically this involves adding a field you can use as a filter.
Implement a QuerySnapshot Listener to return data to all logged in apps if any documents in a collection have been deleted or changed. Write a convenience initializer that accepts a dictionary to create an instance of a class. Use an escaping closure to reload a table view’s data after a listener returns data.
# Watch the collection query. puts "Callback received query snapshot." The snapshot handler will receive a new query snapshot every time the query results change (that is, when a document is added, removed, or modified). Important: As explained above under Events for local changes, you will receive events immediately for your local writes.
You can attach listeners to both a DocumentReference and a Query. As you can see from the API documentation, it turns out that CollectionReference is a subclass of Query, which means you can add a listener to a CollectionReference just fine. A CollectionReference taken as a Query this way will give you all of the documents in that collection, then all of the changes to any of the documents in that collection, just as you see in the documentation (except you don't use any where clauses).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With