如何使 Architecture 的 PagedListAdapter 在配置更改后仍然存在?

How to make Architecture's PagedListAdapter survives configuration changes?

Android 的新 PagedListAdapter 是用于处理数据列表分页的出色库。它对我来说效果很好,只是你如何让它在配置更改(例如屏幕旋转)后仍然存在,就像 Android 架构的 ViewModel 所做的那样?

适配器依赖于 activity 上下文,因此它无法在配置更改后继续存在。相反,该列表将由 ViewModel 配置,它会在配置更改后继续存在并相应地更新 UI。你应该有类似下面的东西。在你的 activity onCreate:

val adapter = CheeseAdapter()
cheeseList.adapter = adapter
// Subscribe the adapter to the ViewModel, so the items in the adapter are refreshed
// when the list changes
viewModel.allCheeses.observe(this, Observer(adapter::setList))

在你的viewModel中:

val allCheeses = dao.allCheesesByName().create(0,
        PagedList.Config.Builder()
                .setPageSize(PAGE_SIZE)
                .setEnablePlaceholders(ENABLE_PLACEHOLDERS)
                .build())!!

我建议你看看这个google sample