【发布时间】:2020-09-17 19:33:35
【问题描述】:
在旋转设备时,我丢失了上一页加载的页面数据。我该如何解决这个问题?
使用下面的实现,只有当前页面的数据被持久化在 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())
}
}
})
}
}
MainActivity
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)
}
【问题讨论】:
标签: android kotlin pagination android-viewmodel android-mvvm