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.
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(this@PetViewModel.genderMutableData) { 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?) {
this@PetViewModel.genderMutableData.postValue("female")
}
Sorry, I'm using Kotlin for example because you don't flag post in Java language.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.