Skip to content

Firestore Get Realtime Updates

Eoin Landy edited this page Nov 7, 2018 · 2 revisions

The contents of this page are based on the original Firebase Documentation

You can listen to a document with the addSnapshotListener() 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.

db.collection("cities").document("SF").addSnapshotListener(onDocSnapshot);
private function onDocSnapshot(document:DocumentSnapshot, error:FirestoreError, realtime:Boolean):void {

}

Events for local changes

Local writes in your app will invoke snapshot listeners immediately. This is because of an important feature called "latency compensation." When you perform a write, your listeners will be notified with the new data before the data is sent to the backend.

Retrieved documents have a metadata.hasPendingWrites property that indicates whether the document has local changes that haven't been written to the backend yet. You can use this property to determine the source of events received by your snapshot listener:

db.collection("cities").document("SF").addSnapshotListener(onDocSnapshot);
private function onDocSnapshot(document:DocumentSnapshot, error:FirestoreError, realtime:Boolean):void {
    if (error) {
        return;
    }
    if (document != null) {
        var source:String = document.metadata.hasPendingWrites ? "Local" : "Server";
        trace("data source: " + source);
    }
}

View changes between snapshots

It is often useful to see the actual changes to query results between query snapshots, instead of simply using the entire query snapshot. For example, you may want to maintain a cache as individual documents are added, removed, and modified.

db.collection("cities").document("SF").addSnapshotListener(onDocSnapshot);
private function onDocSnapshot(document:DocumentSnapshot, error:FirestoreError, realtime:Boolean):void {
    if (error) {
        return;
    }
    if (document != null) {
        for each (var diff:DocumentChange in document.documentChanges){
            if (diff.type == DocumentChangeType.ADDED){
                trace("New city")
            }
            if (diff.type == DocumentChangeType.MODIFIED){
                trace("Modified city")
            }
            if (diff.type == DocumentChangeType.REMOVED){
                trace("Removed  city")
            }
        }
    }
}

Important: The first query snapshot contains added events for all existing documents that match the query. This is because you're getting a set of changes that bring your query snapshot current with the initial state of the query. This allows you, for instance, to directly populate your UI from the changes you receive in the first query snapshot, without needing to add special logic for handling the initial state.

The initial state can come from the server directly, or from a local cache. If there is state available in a local cache, the query snapshot will be initially populated with the cached data, then updated with the server's data when the client has caught up with the server's state.

Detach a listener

When you are no longer interested in listening to your data, you must detach your listener so that your event callbacks stop getting called. This allows the client to stop using bandwidth to receive updates.

sanFran.removeSnapshotListener(onDocSnapshot); //Important!! use a stored var for the DocumentReference

Handle listen errors

A listen may occasionally fail — for example, due to security permissions, or if you tried to listen on an invalid query. (Learn more about valid and invalid queries .) To handle these failures, you can provide an error callback when you attach your snapshot listener. After an error, the listener will not receive any more events, and there is no need to detach your listener.

db.collection("cities").document("SF").addSnapshotListener(onDocSnapshot);
private function onDocSnapshot(document:DocumentSnapshot, error:FirestoreError, realtime:Boolean):void {
    if (error) {
        trace("Error retreiving collection: " + error);
    }
}
Clone this wiki locally