Wal*_*ann 5 android kotlin android-recyclerview android-paging android-paging-library
请帮帮我。
该应用程序仅用于从https://trefle.io接收植物列表并将其显示在 RecyclerView 中。
我在这里使用分页库 3.0。
任务:我想添加一个标题,其中将显示植物总数。
问题:我只是找不到将总项目的值传递给标题的方法。
Data model:
data class PlantsResponseObject(
@SerializedName("data")
val data: List<PlantModel>?,
@SerializedName("meta")
val meta: Meta?
) {
data class Meta(
@SerializedName("total")
val total: Int? // 415648
)
}
data class PlantModel(
@SerializedName("author")
val author: String?,
@SerializedName("genus_id")
val genusId: Int?,
@SerializedName("id")
val id: Int?)
Run Code Online (Sandbox Code Playgroud)
数据源类:
class PlantsDataSource(
private val plantsApi: PlantsAPI,
private var filters: String? = null,
private var isVegetable: Boolean? = false
) : RxPagingSource<Int, PlantView>() {
override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, PlantView>> {
val nextPageNumber = params.key ?: 1
return plantsApi.getPlants( //API call for plants
nextPageNumber, //different filters, does not matter
filters,
isVegetable)
.subscribeOn(Schedulers.io())
.map<LoadResult<Int, PlantView>> {
val total = it.meta?.total ?: 0 // Here I have an access to the total count
//of items, but where to pass it?
LoadResult.Page(
data = it.data!! //Here I can pass only plant items data
.map { PlantView.PlantItemView(it) },
prevKey = null,
nextKey = nextPageNumber.plus(1)
)
}
.onErrorReturn{
LoadResult.Error(it)
}
}
override fun invalidate() {
super.invalidate()
}
}
Run Code Online (Sandbox Code Playgroud)
LoadResult.Page 只接受植物本身的列表。而 DataSource(Repo, ViewModel, Activity) 之上的所有类都无法访问响应对象。
问题:如何将项目总数传递给列表标题?
我将不胜感激任何帮助。
一种方法是使用 MutableLiveData 然后观察它。例如
val countPlants = MutableLiveData<Int>(0)
override fun loadSingle(..... {
countPlants.postValue(it.meta?.total ?: 0)
}
Run Code Online (Sandbox Code Playgroud)
然后是你的回收者视图所在的地方。
pagingDataSource.countPlants.observe(viewLifecycleOwner) { count ->
//update your view with the count value
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1988 次 |
| 最近记录: |