android - 如何在 ViewModel Android 中存储分页数据?
问题描述
在旋转设备时,我丢失了上一页加载的页面数据。我该如何解决这个问题?
使用下面的实现,只有当前页面的数据会保存在 ViewModel 中,而其他所有页面都会丢失。有什么解决办法吗?
API响应(第1页) http://www.mocky.io/v2/5ed20f9732000052005ca0a6
视图模型
class NewsApiViewModel(application: Application) : AndroidViewModel(application) {
val topHeadlines = MutableLiveData<TopHeadlines>()
var networkLiveData = MutableLiveData<Boolean>()
fun fetchTopHeadlines(pageNumber: Int) {
if (!getApplication<Application>().hasNetworkConnection()) {
networkLiveData.value = false
}
val destinationService = ServiceBuilder.buildService(DestinationService::class.java)
val requestCall = destinationService.getTopHeadlines(AppConstants.COUNTRY_INDIA, AppConstants.PAGE_SIZE, pageNumber, AppConstants.NEWS_API_KEY)
requestCall.enqueue(object : Callback<TopHeadlines> {
override fun onFailure(call: Call<TopHeadlines>, t: Throwable) {
Log.e("ANKUSH", "$t ")
}
override fun onResponse(call: Call<TopHeadlines>, response: Response<TopHeadlines>) {
if (response.isSuccessful) {
topHeadlines.postValue(response.body())
}
}
})
}
}
主要活动
fun observeAndUpdateData() {
activity.viewModel.topHeadlines.observeForever {
isDataLoading = false
checkAndShowLoader(isDataLoading)
if (AppConstants.STATUS_OK == it.status) {
it.articles?.let { articles ->
if (articles.size < AppConstants.PAGE_SIZE) {
activity.isAllDataLoaded = true
}
activity.adapter.updateData(articles)
}
}
}
}
fun getTopHeadlines(pageNumber: Int) {
if (activity.isAllDataLoaded) return
isDataLoading = true
checkAndShowLoader(isDataLoading)
activity.viewModel.fetchTopHeadlines(pageNumber)
}
解决方案
您只需要将current page
和the data
您收集到的列表存储在 ViewModel 中。
因此,不要将页码传递给fetchTopHeadlines
函数,而是考虑在 ViewModel 中有一个私有全局变量,并且每次调用 时fetchTopHeadlines
,也要增加页码。
此外,为了防止丢失以前的页面,请考虑在您的 ViewModel 中使用 ArrayList。从服务器获取数据后,首先将所有数据放入 ViewModel 中定义的列表中,然后将该列表发布到您的视图中。
推荐阅读
- c# - 在 C# 中使用 Task.FromResult v/s await
- python - 在python中将消息从Kafka发送到socket.io
- excel - VB6 和 VB7 的 Longptr 数据类型
- r - 如何使矩阵中的 2 列成为减法的日期时间对象
- scala - 你能在 Scala 的 trait 中覆盖私有方法吗?
- matlab - 无法将浮点小数转换为整数
- ruby-on-rails - Rails 可配置授权
- ruby-on-rails - Rails 无法将数据插入数据库
- iis - 用于使用查询字符串回发自身
- c# - Powershell 中的 DataTable.Rows.Find(MultiplePrimaryKey)