问题
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