Paging 3 android java

Pagination in Android with Paging 3, Retrofit and kotlin Flow

Haven’t you asked how does Facebook, Instagram, Twitter, Forbes, etc… let you “scroll infinitely” without reach a “end” of information in their apps? Wouldn’t you like to implement something like that?

This “endless scrolling” feature is commonly called “Pagination” and it’s nothing new. In a brief resume, pagination help you to load chunks of data associated with a “page” index.

Let’s assume you have 200 items to display in your RecyclerView. What you would do normally is just execute your request, get the response items and submit your list to your adapter. We already know that RecyclerView by it’s own is optimized for “recycle our views”. But do we really need to get those 200 items immediately? What if our user never reach the top 100, or top 50? The rest of the non displayed items are still keep on memory.

What pagination does (in conjunction with our API) is that it let us establish a page number, and how many items per page can we load. In that way, we can request for the next page of items only when we reach the bottom of our RecyclerView.

Non library approach

Before paging 3, you could have implemented Pagination by adding some listeners to your RecyclerView and those listeners would be triggered when you reach the bottom of your list. There are some good samples about it, here is a video with a vey detailed explanation (it’s on Indi, but it is understandable anyways).

A real PRODUCTION ready example is on the Plaid app. Look at their InfinteScrollListener class.

Android Jetpack Paging 3 and Flow

Today you gonna learn how to implement Pagination by using paging 3 from the android jetpack libraries. For my surprise the codelab of Paging 3 was one of the most easiest I have ever done. Florina Muntenescu did a great job with each step of the codelab, go check it out and give it a try. If you want to go straight to the sample code, check this pull request and see step by step how I implement paging 3 to this project.

Источник

Как натянуть сыр на страницу, или MVI Paging3 в Android

Привет! Меня зовут Георгий Бердников. Я разработчик в компании 65apps, занимаюсь созданием мобильных приложений на Android. Сегодня расскажу о том, как совместить приятное с полезным, поймать двух зайцев и журавля с неба инженеру, перед которым встала сложная задача реализовать постраничную загрузку в приложении.

Библиотека Paging3 упрощает работу с пагинацией. Она всё делает сама: вам не нужно заниматься ручной передачей данных по заветам популярных архитектур, таких как MVI, MVVM и MVP. Снаружи задумка кажется хорошей, но она может стать ложкой дёгтя в бочке мёда. Инструменты, взаимодействующие с общим состоянием (к таким относятся, например, средства отладки в фреймворке MVIKotlin), не смогут контактировать с Paging3.

Читайте также:  Cheat among us android mod menu

В статье я покажу, как решить эту проблему. В качестве плацдарма для модификаций был выбран небезызвестный сэмпл от Google, в который мы и внедрим подставьте сюда фреймворк своей мечты (в статье используется вышеупомянутый MVIKotlin). Наш взор падёт только на Paging3, функциональность вставки и удаления предметов оставим в стороне.

Источник данных

Всё, что связано с получением данных — Entity, DAO, база данных — останется неизменным. Эта статья будет вкусной! 🧀🧀🧀

Слой модели

В первую очередь назначим ответственного за получение данных. Это будет CheeseSource:

Nullable-элементы в списке — способ реализации плейсхолдеров, аналогичный тому, что AsyncPagingDataDiffer.getItem() может вернуть null.

Затем создадим способ передачи данных между компонентами. Встречайте — CheeseStore:

Intent один, и его название говорит само за себя: он отвечает за загрузку элементов при скроллинге на определенный индекс (о скроллинге чуть позже). Intent и State, проще говоря, являются входом и выходом метода CheeseSource.get(), вокруг которого вертится весь слой.

Совместить все входы и выходы и понять смысл жизни поможет CheeseExecutor:

Как можно заметить, он не только отвечает на намерения, но и отдаёт первую порцию данных в начале работы Store.

Настало время для самой важной части статьи: реализация CheeseSource!

CheeseDatabaseSource постоянно отслеживает Pager.flow и передаёт PagingData из него в dataDiffer, используемый нами вовсе не для измерения разницы между списками, а для получения заветных данных!

noopListUpdateCallback нужен лишь для создания dataDiffer.

Сакральный метод get() разделяется на две части, одна из которых отвечает за первичную загрузку данных, а вторая — за последующие. Если элементов в dataDiffer не оказалось, мы ждём их появления. Если они есть — передаем новый индекс и ждём, пока закончится загрузка.

ItemSnapshotList из Paging3 реализует интерфейс List , поэтому мы вольны без каких-либо манипуляций вернуть snapshot().

Наконец, соберём всё в CheeseStoreFactory:

Отображение данных

В первую очередь, создадим CheeseView:

UI-часть сэмпла придется немного поменять. Нас, по вышеописанным причинам, не устраивает CheeseAdapter, который наследуется от PagingDataAdapter. Однако вполне устраивает уже написанный CheeseViewHolder, поэтому мы будем управлять списком сами, сделав RecyclerView.Adapter родителем CheeseAdapter и используя AsyncListDiffer:

Вы можете использовать любые удобные инструменты работы со списками, например, AdapterDelegates, но во имя простоты в этой статье используется минимум библиотек.

Поскольку нам самим необходимо уведомлять слой данных о том, что мы хотим отобразить новый контент, создадим OnScrollListener, уведомляющий о каждом новом элементе в области видимости пользователя:

Дело за малым — использовать всё в реализации CheeseView:

Череда изменений завершена. Итоговое состояние проекта можно посмотреть здесь. Он смог совместить в себе MVI, широко используемый в новейших мобильных приложениях, и Paging3 с великими возможностями, а значит ничто теперь не остановит вас на пути к молниеносному созданию производительных приложений со списками!

Что дальше

Paging3 обширна, и не все её возможности взаимодействия с MVI могли быть рассмотрены в этой статье. Если найдёте другие особенности интеграции — указывайте в комментариях или пишите мне в телеграм @berdorge.

Еще одна задача на будущее, помимо внедрения — оптимизировать быстродействие. Ну и, если тема вызовет интерес, можно подумать над тем, чтобы оформить все в виде отдельной библиотеки.

ПС. остался самый главный вопрос: какой сыр мне выбрать, чтобы отпраздновать столь яркую победу? 🙂

Читайте также:  Строительные калькуляторы для андроид

Источник

Paging 3 Android Example in Java – Building Movies Application

Paging 3 helps to load the collection of data from the server, local storage, or both. This library is part of Android Jetpack and seamlessly integrates with other components. Paging 3 helps you to reduce network requests that will reduce bandwidth usages. It supports Kotlin coroutines and Flow, as well as LiveData and RxJava. It also provides support for retry, error handling, and refresh are out of the box features. In this article, we will implement Paging 3 Android Example in Java language.

In this example, we will build a movies application. This application will load movies from API and display them in a Recyclerview. Furthermore, we will use all the latest Jetpack library components. You can download the source code and demo application from the following links.

Paging 3 Android Example – Building Movies Application

We will use The Movie Database API to get popular movies. The application contains a list of movies. Movies will be shown using a RecyclerView. I will try to explain each part of the code at the beginner level.

1. Application architecture

I am following the recommended Android app architecture for building the application. There are four layers to the application.

  • Remote Data Source layer
  • Repository layer
  • ViewModel layer
  • UI layer

Remote Data Source layer

The component in the Remote Data Source layer is Retrofit. That will call The Movie Database API. Results will be exposed to PagingSource.

Repository layer

PagingSource provides logic to retrieve information from an API or local database. It loads the data page by page. PagingSource object can load information single data source.

ViewModel layer

Pager provides API to construct Paging Data objects exposed by Paging Source. It queries a PagingSource object and stores the result. PagingData contains data of a page or an error.

UI layer

The primary component of paging in the UI layer is PagingDataAdapter. A RecyclerView adapter that handles paginated data. We have to subscribe to Flow

in the UI layer.

Furthermore, we have LoadStateAdapter in the UI layer. It handles the load state of the Paging. There are three LoadState.

  • If there is no active load operation and no errors, then LoadState is a LoadState.NotLoading object.
  • If there is an active load operation, then LoadState is a LoadState.Loading object.
  • LoadState is a LoadState.Error object If there is an error while loading.

2. Setting up dependencies

This application is build using modern android architecture components for example ViewModel, Lifecycle, and ViewBinding. For calling API we are using Retrofit and okhttp3 libraries. Furthermore, for converting JSON response to java object Gson library is used. Add the following code to app-level build.gradle file.

  • Enable VIewBinding

Note : Rebuild project to generate ViewBinding classes.

  • Enable Java 8

3. Create model classes

API returns JSON response. This response needs to be converted to an equivalent Java object. Create new class Model > Movie.java. These classes are created using jsonschema2pojo.

Create another class Model > MovieResponse.java.

4. Create API Client

To make HttpRequest we are using Retrofit and OkHttpClient. Firstly we need API Key to use The Movie Database API.

  1. Create an account at The Movie Database.
  2. Go to Settings > API > New API Key. Create a new API Key and keep it with you.

Create new class API > APIClient.java. Enter your API key in the query parameter placeholder in the below class.

5. Implement PagingSource

PagingSource contains data retrieval logic. Here make a Retrofit request passing page number. We will use RxPagingSource which loads data from only one source. Create new class Paging > MoviePagingSource.java.

Читайте также:  Смена страны для андроид

6. Define a RecyclerView adapter

Paging Library provides PagingDataAdapter for creating RecyclerView adapter.

Before Creating Adapter we need to create the layout of a single movie item. Create a new layout movie_item.xml.

Create new class Adapter > MoviesAdapter.java extending PagingDataAdapter class as shown below.

Now one last thing is to create a Comparator. It will avoid duplication of items in RecyclerView. Create new class Util > MovieComparator.java.

7. Handle loading, errors and retry using Paging 3

While loading page data we will show a loading view. If there is an error while loading then we will show an error message and a retry button. It can be achieved by using LoadStateAdapter. Firstly let’s create a layout for the load item load_state_item.xml.

Create new class Adapter > MoviesLoadStateAdapter.java.

8. Add spacing in RecyclerView Items

In this example, each row of RecyclerView will have two movie items. In between each movie item we have to add space. To add this space we have to create ItemDecoration class. Create a new class Util > GridSpace.java.

9. Set up a stream of PagingData

According to modern android architecture, we will add our stream of PagingData in ViewModel. Pager class provides us PagingData stream from PagingSource. PagingConfig class provides Pager Paging options. Paging library supports multiple data streams like Flowable, Observable as well as Flow and LiveData. In this application, we will use Flowable from the RxJava library. Create a new class ViewModel > MainActivityViewModel.java.

10. Display Paging Data in RecyclerView

Firstly, create layout for activity activity_main.xml. Layout contains RecyclerView widget.

Now that you have created PagingSource, a stream of PagingData and PagingDataAdapter. Let’s connect these parts together and display them in your activity.

  1. Create PagingDataAdapater instance passing new DiffUtil.ItemCallback<>.
  2. Initialize ViewModel.
  3. Subscribe to the stream of PagingData. Inside subscribe submit data to PagingDataAdapater upon receiving new data.
  4. Set layout manager as GridLayoutManager
  5. Add Space ItemDecoration to RecyclerView
  6. Set ConcatAdapter as RecyclerView adapter by combing MoviesAdapter with MoviesLoadStateAdapter.
  7. Finally set span size of GridLayoutManager based on ViewType.

Create new activity class Activity > MainActivity.java.

11. Run the Application

Note: Add Internet permission to your mainfest.xml file. Lastly, Run the application and experience of Paging Library Magic.

12. References

Conclusion

You can use Paging 3 Library to load data from the network, local storage, or both. Above all seamless integration of Paging in other android architecture components are just awesome.

I hope you understand Paging 3 Library integration. If you still have any queries, please post them in the comments section below, I will be happy to help you.

Hello there, My name is Amardeep founder of loopwiki.com. I have experience in many technologies like Android, Java, Php, etc. In this variety of technologies, I love Android App Development. If you have any idea and you want me to develop for you then let’s have chat Conatct

Android CoordinatorLayout Examples – Toolbar, Collapsing Toolbar, Tabs, ViewPager

4 Comments

thnx for this education .

please help me to set PagingConfig maxSize from api model ?

can implement paging3 network + database, thanks

How to implement local database caching in this

How would you do it so that after orientation change, you’re displaying (roughly) the same movies as before?

Источник

Оцените статью