Displaying large lists of items in a performant manner is a very common use case in both mobile and web apps. This story describes how this pattern can be implemented using Firebase.
In our example we push items to a list using Firebase auto-generated keys. These keys have the property to be unique and to be ordered chronologically, in ascending order. For instance, to display the ten most recent entries in our list, we limit our query to the last time item and reverse the order of the query result.
An easy approach to pagination is to increase the number of items fetched by the query for each new page. Every time we receive new items, we increase the page number. Before every new query, we dispose of the observer of the previous query which won’t be used anymore.
A more efficient way to implement this pattern is to only fetch new items for each page. This can be done by using endAt(). First we keep a map containing the content of each page. This is extremely useful in case the content of a page gets updated. When we receive items, we keep the first identifier in the sequence in order to use it in the next query. This is assuming that we want to fetch items chronologically in descending order.
This strategy is implemented in the snippet below.