I am attempting to create a chat app using firestore. My message class has a timestamp in the form of a Date
object. I would like the chat activity to load the most recent X messages, and add any new ones to the bottom in realtime using a SnapshotListener
. Below is what I have so far, which sorts the X oldest messages by timestamp, but ignores all messages after and does not display any new messages when they are added if a full X messages are already pulled down.
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
Query query = mCollection.orderBy("timestamp",Query.Direction.ASCENDING).limit(mCurrentPage * TOTAL_ITEMS_TO_LOAD);
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
for (DocumentChange documentChange : queryDocumentSnapshots.getDocumentChanges()) {
switch (documentChange.getType()) {
case ADDED:
Message message = documentChange.getDocument().toObject(Message.class);
mMessages.add(message);
mAdapter.notifyDataSetChanged();
}
}
}
});
Edit: I've removed superfluous code. Sorting by descending causes messages to be laid out like this when queried, with newest messages queried appearing at the top, which doesn't work, because I want newest messages at the bottom descending upward:
- queriedmessage5<-newest queried
- queriedmessage4
- queriedmessage3
- queriedmessage2
- queriedmessage1<-oldest queried
- newmessage1<-added after query
Reversing the RecyclerView using setReverseLayout via the layout manager corrects the order of the queried messages, but then inserts new messages at the top of the RecyclerView :
- newmessage1<-added after query
- queriedmessage1<-oldest queried
- queriedmessage2
- queriedmessage3
- queriedmessage4
- queriedmessage5<-newest queried
You'll need to order the messages descending to be able to get the 10 most recent messages.
This will give you the most recent items. As you add messages, you'll get the newest ones, and you'll get a
REMOVED
event for the messages that fall out of the query.Given that you request the messages in reverse chronological order, you'll have to reverse the message client side again, to show them in the correct order in your app.