androidandroid-architecture-componentsandroid-livedataandroid-architectureandroid-paging

How to make Architecture's PagedListAdapter survives configuration changes?


Android's new PagedListAdapter is a great library for handling paging on a list of data. It works well for me, only that how do you make it survives configuration changes (such as screen rotation) just like how Android Architecture's ViewModel do ?


Solution

  • The adapter depends on activity context so it wont survive configuration changes. Instead, the list will be configured by the ViewModel, which survives configuration changes and updates UI accordingly. You should have something like the following. In your 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))
    

    In your viewModel:

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

    I recommend you take a look to this google sample