在旋转设备时,我丢失了上一页加载的页面数据。我该如何解决这个问题?
使用下面的实现,只有当前页面的数据会保存在 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())
}
}
})
}
}
主要 Activity
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 中使用私有(private)全局变量,并且每次调用 fetchTopHeadlines
, 也增加页码。
此外,为了防止丢失以前的页面,请考虑在您的 ViewModel 中使用 ArrayList。从服务器获取数据后,首先将所有数据放入 ViewModel 中定义的列表中,然后将该列表发布到您的 View 中。
Here is a sample that helps you dealing with it.
关于android - 如何在 ViewModel Android 中存储分页数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62099374/