Updated 6 September 2019
The Paging library is a part of Android Jet Pack. It will help you load and display small chunks of data at a time. Loading partial data on demand reduces the usage of network bandwidth and system resources.
For this, we will require to add the following dependencies in the project’s build.gradle file:
1 2 3 4 5 6 7 8 9 10 11 |
dependencies { def paging_version = "2.1.0" 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 } |
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 then a new instance of PagedList is emitted to the observable data holder from a PagedList or RxJava2-based object. As PagedList objects are generated, your app’s UI presents their contents, all while respecting your UI controllers’ lifecycle.
We can define our own paging configuration. Like the items per page and prefetched items count and many more things. And then get the data by network call or local database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
PagedList.Config myPagingConfig = new PagedList.Config.Builder() .setPageSize(50) .setPrefetchDistance(150) .setEnablePlaceholders(true) .build(); // The Integer type argument corresponds to a PositionalDataSource object. DataSource.Factory<Integer, Concert> myConcertDataSource = concertDao.concertsByDate(); LiveData<PagedList<Concert>> concertList = new LivePagedListBuilder<>(myConcertDataSource, myPagingConfig) .setFetchExecutor(myExecutor) .build(); |
Connect your UI to your view model. You can connect an instance of LiveData<PagedList> to a PagedListAdapter, as shown in the following code snippet:
1 2 3 4 5 6 7 8 9 10 11 |
public class ExampleActivity extends AppCompatActivity { private ExampleAdapter adapter = new ExampleAdapter(); private ExampleViewModel viewModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); viewModel = ViewModelProviders.of(this).get(ExampleViewModel.class); viewModel.ExampleList.observe(this, adapter::submitList); } } |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.