Last active
August 19, 2017 18:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)) }