简体   繁体   中英

Adding a Snapshot Listener to a Collection Firestore

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?)

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).

I did a quick check on my code to confirm.

You can do a code like this, without a problem:

val db = FirebaseFirestore.getInstance()
val query = db.collection("Quotes_historyfavorites").document(userId)
                .collection(FireBaseConstants.QuoteCollection.FAVORITE)
                .orderBy("Added", Query.Direction.DESCENDING)

I am not sure if a top level collection would be possible, but I believe that you would face a moneyissue before having a perfomance issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM