title: Sort X most recent Firestore documents Ascending by timestamp, and add in real time
body: <p>I am attempting to create a chat app using firestore. My message class has a timestamp in the form of a <code>Date</code> 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 <code>SnapshotListener</code>. Below is what I have so far, which sorts the X <em>oldest</em> 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.</p>
  
  <pre><code> 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&lt;QuerySnapshot&gt;() {
              @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();
  
                      }
                  }
              }
          });
  </code></pre>
  
  <p>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:</p>
  
  <ul>
  <li>queriedmessage5&lt;-newest queried</li>
  <li>queriedmessage4</li>
  <li>queriedmessage3</li>
  <li>queriedmessage2</li>
  <li>queriedmessage1&lt;-oldest queried</li>
  <li>newmessage1&lt;-added after query</li>
  </ul>
  
  <p>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 :</p>
  
  <ul>
  <li>newmessage1&lt;-added after query</li>
  <li>queriedmessage1&lt;-oldest queried</li>
  <li>queriedmessage2</li>
  <li>queriedmessage3</li>
  <li>queriedmessage4</li>
  <li>queriedmessage5&lt;-newest queried</li>
  </ul>