【问题标题】:How to store Pagination data in ViewModel Android?如何在 ViewModel Android 中存储分页数据?
【发布时间】: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


    【解决方案1】:

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

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

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

    Here is a sample that helps you dealing with it.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 2021-10-16
      • 2020-09-13
      • 2013-08-01
      相关资源
      最近更新 更多