为什么在Firestore CollectionReference上两次调用addSnapshotListener?

时间:2019-07-18 06:26:49

标签: android firebase google-cloud-firestore

我使用以下代码向Firestore数据库添加注释:

String currentTime = GetTimeStampFunction()
Comment mComment = new Comment(comment, currentUser.getUid(), null, currentTime);
    firebaseFirestore
        .collection(POSTS)
        .document(postId)
        .collection(COMMENTS)
        .add(mComment);

此外,无论何时将注释添加到Firestore中,我都编写了一个snapshotListener来更新recyclerview:

private CollectionReference commentsReference;

@Override
protected void onCreate(Bundle savedInstanceState)
{
     ........
     commentsReference = firebaseFirestore
            .collection(POSTS)
            .document(postId)
            .collection(COMMENTS);
     ........
}

@Override
protected void onStart()
{
    super.onStart();
    commentsReference
        .addSnapshotListener((Activity) context, new EventListener<QuerySnapshot>()
        {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots,
                                @Nullable FirebaseFirestoreException e)
            {
                if (e != null)
                {
                    Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty())
                {
                    comments = new ArrayList<>();
                    for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots)
                    {
                        Comment comment = snapshot.toObject(Comment.class).withId(snapshot.getId());
                        comments.add(comment);
                    }

                    CommentsListAdapter adapter = new CommentsListAdapter(context, comments);
                    commentsRecyclerView.setAdapter(adapter);
                    System.out.println("List Updated");        }
            }
        });
}

所以,问题在于,每当我添加注释时,此addSnapshotListener都会被调用两次(“列表更新”被打印两次)。我正在使用this tutorial中给出的确切代码。那么,为什么会这样呢?

编辑: 我只是发现没有。的通话次数不是两次。它比没有多。集合中的文档数量,即否。文档数量为3,快照侦听器称为4次。

0 个答案:

没有答案