Search code examples
androidfirebasegoogle-cloud-firestoreandroid-livedataandroid-paging-3

How to Use FirebaseFirestore with Paging 3 Library?


I wanted to build an application like Twitter where I have to display a list of data sets with live updates for counting like and comments in real time.

For that, I am using

  1. RecyclerView - for displaying list of scrollable data
  2. Jetpack LiveData - for observing changes and notifying observers.
  3. Firestore - As a backend for getting realtime data with snapshot changes.
  4. Paging 3 - for loading large set of data into list by chuncks.

But how would I implement the firestore query with PaggingSource class by emitting live changes to the list?

class FirebasePagingSource() : PagingSource<QuerySnapshot,ItemModel>() {

override fun getRefreshKey(state: PagingState<QuerySnapshot, ItemModel>): QuerySnapshot? {
 // Need guidance for implementation
}

override suspend fun load(params: LoadParams<QuerySnapshot>): LoadResult<QuerySnapshot, ItemModel> {
 //Need guidance for implementation
} }

Here ItemModel is a data class

2. ItemListLiveData Class

class FirestoreQueryLiveData(private val query: Query)
: LiveData<List<Item>>(), EventListener<QuerySnapshot> {

private lateinit var registration: ListenerRegistration

override fun onActive() {
    super.onActive()
    registration = query.addSnapshotListener(this)
}

override fun onInactive() {
    super.onInactive()
    registration.remove()
}

override fun onEvent(snapshot: QuerySnapshot?, error: FirebaseFirestoreException?) {
    snapshot?.let {
        val documents= mutableListOf<Item>()
        for (document in snapshot.documents) {
            document.toObject(Item::class.java)?.let {
                documents.add(it)
            }
        }
        postValue(documents)
    }
} }

Solution

  • There are plenty of useful guides online. In general, you can set a stream of paged data from Firestore into a Recycler View and from there it is simply a matter of paginating each request.

    This can be a lengthy and involved process, so I will link a recommended tutorial, its source, and the relevant youtube guide.