Skip to content

Instantly share code, notes, and snippets.

@fullkomnun
Last active August 19, 2017 18:08
Show Gist options
  • Save fullkomnun/a60d8540a87708619f531887df364680 to your computer and use it in GitHub Desktop.
Save fullkomnun/a60d8540a87708619f531887df364680 to your computer and use it in GitHub Desktop.
A util for updating RecyclerView while making sure LayoutManager's state is properly maintained through update operation, avoiding some 'Inconsistency Detected' errors
@file:JvmName("RecyclerViewUtils")
package com.ornoyman.core.ui.recyclerview
import android.support.v7.widget.RecyclerView
import io.reactivex.functions.Action
/**
* Allows safely updating the backing data and notifying recycler view.
* If adapter is currently in lockdown state, will post update action to avoid illegal state error.
* Saves and restores scrolling state so hopefully updates will not result in
* the dreaded 'Inconsistency detected' error.
*/
fun RecyclerView.safeUpdate(update: Action) = this.safeUpdate(update::run)
/**
* Allows safely updating the backing data and notifying recycler view.
* If adapter is currently in lockdown state, will post update action to avoid illegal state error.
* Saves and restores scrolling state so hopefully updates will not result in
* the dreaded 'Inconsistency detected' error.
*/
inline fun RecyclerView.safeUpdate(crossinline update: () -> Unit) {
val safeUpdate = createSafeUpdate(update)
if (!isComputingLayout) safeUpdate() else post { safeUpdate() }
}
inline fun RecyclerView.createSafeUpdate(crossinline update: () -> Unit): () -> Unit {
return {
val state = layoutManager?.onSaveInstanceState()
update()
layoutManager?.onRestoreInstanceState(state)
}
}
@fullkomnun
Copy link
Author

Kotlin Usage
private fun updateRecyclerView(rv: RecyclerView, data: List<MyData>) { rv.safeUpdate { adapter.setData(data) } }

Java Usage
private void updateRecyclerView(RecyclerView rv, List<MyData> data) { RecyclerViewUtils.safeUpdate(rv, () -> adapter.setData(data)) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment