airbnb / epoxy

Epoxy is an Android library for building complex screens in a RecyclerView
https://goo.gl/eIK82p
Apache License 2.0
8.5k stars 733 forks source link

Restore layout manager state with multiple requestModelBuild invocation #876

Closed manueldidonna closed 4 years ago

manueldidonna commented 4 years ago

I used to restore the scroll position of a recyclerview using the layout manager state. I restore that state when epoxycontroller buildModels() has run and changes have been notified to the adapter. If I add a carousel model it doesn't work anymore. I can't understand why that happens

manueldidonna commented 4 years ago

My Controller stores some properties received by different reactive sources, so the models rapidly change after state restoration. I solved that problem by building the models when all the data had been set at least once (in my case this means that they weren't null).


// onRestoreState
epoxyController.onNextModelBuild {
    recycler.layoutManager?.onRestoreInstanceState(bundle[SAVED_STATE])
}

inline fun EpoxyController.onNextModelBuild(crossinline action: (DiffResult) -> Unit) {
    addModelBuildListener(object : OnModelBuildFinishedListener {
        override fun onModelBuildFinished(result: DiffResult) {
            removeModelBuildListener(this)
            action(result)
        }
    })
}