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

How to store Pagination data in ViewModel Android?

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

通过以下实现,只有当前页面的数据保留在 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)
    }

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

所以不要将页码传递给 fetchTopHeadlines 函数,而是考虑在 ViewModel 中有一个私有全局变量,并且每次调用 fetchTopHeadlines 时,也增加页码.

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

Here is a sample that helps you dealing with it.