Difference between get() and onSnapshot() in Cloud Firestore

前端 未结 1 1865
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 19:43

I am reading some data from Firebase\'s Cloud Firestore but I\'ve seen several ways to do it. The example I saw used the get and onSnapshot function like this:



        
相关标签:
1条回答
  • 2020-12-15 20:36

    As explained in the doc:

    There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries:

    • Call a method to get the data.
    • Set a listener to receive data-change events.

    When you set a listener, Cloud Firestore sends your listener an initial snapshot of the data, and then another snapshot each time the document changes.

    When you use get() you "retrieve the content of a single document" only once. It's a kind of "get and forget": If the document changes in the (back-end) Firestore database you will need to call get() again to see the change.

    On the opposite, if you use the onSnapshot() method you constantly listen to a document as explained in the doc:

    You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.

    As explained in these docs, these two methods apply to one document or to a collection of documents (including a query).

    0 讨论(0)
提交回复
热议问题