Removing ChildEventListener

元气小坏坏 提交于 2019-12-24 11:29:25

问题


I'm using Firebase childEventListener which is added N-number of times to a Node to get data from the DB.

Now I'm trying to remove the childEventListener and it does not seem to work and I get duplicate data.

    query = FirebaseDatabase.getInstance().getReference()
            .child("chat")
            .child("room-messages")
            .child(roomID)
            .orderByChild("timestamp")
            .limitToLast(index);

    paginationListener = query.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Log.d(TAG, dataSnapshot.getKey() + " - Single Value");
            try {
                Message message = dataSnapshot.getValue(Message.class);
                message.setId(dataSnapshot.getKey());
                EventBus.getDefault().post(new GetPaginatedMessage(message));
            } catch (RuntimeException e) {
                Log.d(TAG, "Type Cast Exception Caught");
            }

        }

and removing the listener like

 if (query != null && paginationListener != null) {
        query.removeEventListener(paginationListener);
    }

It doesn't seem to work and I get duplicate data. Any help is appriciated


回答1:


Calling removeEventListener() removes the listener from that location. It will not fire events for any data received after you call it. It may still fire some events for data it's already received.

Jonny's answer on the firebase-talk group about this same behavior:

events are queued up asynchronously and potentially run on a different thread, so there might have been events queued up before you call removeEventListener.



来源:https://stackoverflow.com/questions/46140289/removing-childeventlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!