Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase : Firestore : What is the equivalent of ChildEventListener found in Realtime Database

I have this for Firestore.

FirebaseFirestore   db  = FirebaseFirestore.getInstance();
        CollectionReference ref = db.collection("app/appdata/notifications");
        ref.addSnapshotListener((snapshot, e) -> {
            if (e != null) {
                Log.w(TAG, "Listen failed.", e);
                return;
            }

            for (DocumentSnapshot x : snapshot.getDocuments()) {
                System.out.println(x.getData());
            }
        });

But I don't want to use that loop, instead I need to only get the new children. I'd like something like the following as seen in the Realtime Db.

ref.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
        Post newPost = dataSnapshot.getValue(Post.class);
        System.out.println("Author: " + newPost.author);
        System.out.println("Title: " + newPost.title);
        System.out.println("Previous Post ID: " + prevChildKey);
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {}

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {}

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}

    @Override
    public void onCancelled(DatabaseError databaseError) {}
});
like image 734
Relm Avatar asked Dec 23 '22 13:12

Relm


1 Answers

You need to use .getDocumentChanges() on the QuerySnapshot object to get the list of changes since the last snapshot. This is equivalent to the child-change events in Realtime Database. For example:

FirebaseFirestore   db  = FirebaseFirestore.getInstance();
CollectionReference ref = db.collection("app/appdata/notifications");
ref.addSnapshotListener((snapshot, e) -> {
    if (e != null) {
        Log.w(TAG, "Listen failed.", e);
        return;
    }

    for (DocumentChange dc : snapshots.getDocumentChanges()) {
        switch (dc.getType()) {
            case ADDED:
                // handle added documents...
                break;
            case MODIFIED:
                // handle modified documents...
                break;
            case REMOVED:
                // handle removed documents...
                break;
            }
        }
    }
});

See https://firebase.google.com/docs/firestore/query-data/listen#view_changes_between_snapshots for more details.

like image 160
Michael Lehenbauer Avatar answered Dec 27 '22 03:12

Michael Lehenbauer