Android Architecture Component now introduced Paging Library, which is great.
According to the official demo The DataSource.Factory
now supports map
and mapByPage
methods, which means we may transform items in one DataSource
.
But DataSource
and DataSource.Factory
should be in the model layer, not the Presentor/View layer. However, there are plenty of times when we want to transform data in our Adapter(for RecyclerView or ListView), and obviously, this is the Presentor/View layer logic. By now, an Adapter holds an instance of PagedList
, but PageList
can't support these operations, which is kinda awkward. Besides, there are still times when we want to add items or remove items to/from a PagedList
.
So this is a feature request:
Support item transformations on a PagedList
Support item adding/removing to/from a PagedList
Any discussion is welcomed.
Paging 3.0 is a complete re-write of the library. It uses Kotlin, and it has first-class support for Kotlin coroutines and flow. It also has some new features. For example, it supports headers and footers, and it has retry and refresh mechanisms.
The Paging library helps you load and display pages of data from a larger dataset from local storage or over network. This approach allows your app to use both network bandwidth and system resources more efficiently.
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.
I think you need use transformations for PagedList
instead of LiveData<List<YourModel>>
.
For example, I have a list of Pet
, each Pet
have gender
. I need to show paging of Pet
and filter gender
in runtime.
So, my Dao interface may be:
@Dao inteface PetDao { @Query("SELECT * FROM Pet WHERE Pet.gender = :gender ORDER BY Pet.id ASC") fun getPetsByGenderDataFactory(gender: String?): Datasource.Factory<Int, Pet> }
In ViewModel
class, I will use Transformations
to filter LiveData<PagedList<Pet>>
instead of LiveData<List<Pet>>
:
class PetViewModel { private val genderMutableData: MutableLiveData<String> = MutableLiveData() private val petItemsData: LiveData<PagedList<Pet>> = Transformations.switchMap([email protected]) { petGender -> LivePagedListBuilder(AppDatabase.getDefault().getPetDao().getPetsByGenderDataFactory(petGender), 20).build() } }
When user change gender
of Pet
, you just update value of genderMutableData
, it will trigger data source for petItemsData
and update Pet
items:
fun updatePetItemsWithNewGender(gender: String?) { [email protected]("female") }
Sorry, I'm using Kotlin for example because you don't flag post in Java language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With