如何在Android的ViewModel中存储分页数据?

问题描述 投票:1回答:1

在旋转设备时,我丢失了先前加载的页面数据。我该如何解决?

通过下面的实现,只有当前页面的数据保留在ViewModel中,而所有其他页面都丢失了。有什么解决办法吗?

API响应(第1页)http://www.mocky.io/v2/5ed20f9732000052005ca0a6

ViewModel

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
1个回答
1
投票

您只需要存储在ViewModel的列表中收集的current pagethe data

因此,请勿将页码传递给fetchTopHeadlines函数,而应考虑在ViewModel中使用私有全局变量,并且每次调用fetchTopHeadlines时,也都应增加页码。

为了防止丢失前一页,请考虑在ViewModel中使用ArrayList。从服务器获取数据后,首先将所有数据放入ViewModel定义的列表中,然后将该列表发布到您的View。

Here is a sample that helps you dealing with it.

© www.soinside.com 2019 - 2024. All rights reserved.