Last active
August 7, 2020 08:14
-
-
Save nanodeath/14e2688919dba81fbbe8cb76047a88dc to your computer and use it in GitHub Desktop.
Bind your Android data-binding ObservableList to a RecyclerView
This file contains hidden or 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
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