Skip to content

Instantly share code, notes, and snippets.

@nanodeath
Last active August 7, 2020 08:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanodeath/14e2688919dba81fbbe8cb76047a88dc to your computer and use it in GitHub Desktop.
Save nanodeath/14e2688919dba81fbbe8cb76047a88dc to your computer and use it in GitHub Desktop.
Bind your Android data-binding ObservableList to a RecyclerView
import android.databinding.ObservableList
import android.support.v7.widget.RecyclerView
/**
* Links an [ObservableList] to a [RecyclerView], so that whenever the list is changed, the view is
* updated.
*/
class RecyclerViewAdapterOnListChangedCallback<T>(
private val adapter: RecyclerView.Adapter<*>
) : ObservableList.OnListChangedCallback<ObservableList<T>>() {
override fun onChanged(sender: ObservableList<T>) {
adapter.notifyDataSetChanged()
}
override fun onItemRangeRemoved(sender: ObservableList<T>, positionStart: Int, itemCount: Int) {
adapter.notifyItemRangeRemoved(positionStart, itemCount)
}
override fun onItemRangeMoved(sender: ObservableList<T>, fromPosition: Int, toPosition: Int, itemCount: Int) {
repeat(itemCount) { i ->
adapter.notifyItemMoved(fromPosition + i, toPosition + i)
}
}
override fun onItemRangeInserted(sender: ObservableList<T>, positionStart: Int, itemCount: Int) {
adapter.notifyItemRangeInserted(positionStart, itemCount)
}
override fun onItemRangeChanged(sender: ObservableList<T>, positionStart: Int, itemCount: Int) {
adapter.notifyItemRangeChanged(positionStart, itemCount)
}
}
/** Convenience function to link an [ObservableList] and a [RecyclerView.Adapter]. */
fun <T> ObservableList<T>.subscribeRecycler(adapter: RecyclerView.Adapter<*>) {
addOnListChangedCallback(RecyclerViewAdapterOnListChangedCallback(adapter))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment