Paging 2 library overview Part of Android Jetpack.
The Paging Library helps you load and display small chunks of data at a time. Loading partial data on demand reduces usage of network bandwidth and system resources.
This guide provides several conceptual examples of the library, along with an overview of how it works. To view complete examples of how this library functions, try out the codelab and samples from the additional resources section.
Setup
To import Paging components into your Android app, add the following
dependencies to your app's build.gradle file:
Groovy
dependencies { def paging_version = "2.1.2" implementation "androidx.paging:paging-runtime:$paging_version" // For Kotlin use paging-runtime-ktx // alternatively - without Android dependencies for testing testImplementation "androidx.paging:paging-common:$paging_version" // For Kotlin use paging-common-ktx // optional - RxJava support implementation "androidx.paging:paging-rxjava2:$paging_version" // For Kotlin use paging-rxjava2-ktx }
Kotlin
dependencies { val paging_version = "2.1.2" implementation("androidx.paging:paging-runtime:$paging_version") // For Kotlin use paging-runtime-ktx // alternatively - without Android dependencies for testing testImplementation("androidx.paging:paging-common:$paging_version") // For Kotlin use paging-common-ktx // optional - RxJava support implementation("androidx.paging:paging-rxjava2:$paging_version") // For Kotlin use paging-rxjava2-ktx }
Library architecture
This section describes and shows the main components of the paging library.
PagedList
The Paging Library's key component is the
PagedList class, which loads
chunks of your app's data, or pages. As more data is needed, it's
paged into the existing PagedList object. If any loaded data changes, a new
instance of PagedList is emitted to the observable data holder from a
LiveData or RxJava2-based object. As
PagedList objects are generated,
your app's UI presents their contents, all while respecting your UI controllers'
lifecycles.
The following code snippet shows how you can configure your app's view model to
load and present data using a LiveData holder of PagedList objects:
Kotlin
class ConcertViewModel(concertDao: ConcertDao) : ViewModel() { val concertList: LiveData<PagedList<Concert>> = concertDao.concertsByDate().toLiveData(pageSize = 50) }
Java
public class ConcertViewModel extends ViewModel { private ConcertDao concertDao; public final LiveData<PagedList<Concert>> concertList; // Creates a PagedList object with 50 items per page. public ConcertViewModel(ConcertDao concertDao) { this.concertDao = concertDao; concertList