Usage
| This documentation was generated with the assistance of AI. Please report any inaccuracies. |
This page shows how to drive a RecyclerView adapter with RecyclerViewManager (package
com.irurueta.android.recyclerviewmanager). The examples use the same Item model, adapter and view holder as the
sample app.
How it works
1. Describe your data
First decide two things about your data model:
-
what identifies an item, so the same item can be recognized in the old and the new list (usually an id); and
-
what makes its content different, so the manager knows when an item that is still present must be rebound.
// `id` identifies the item; `name` is its displayed content
data class Item(val id: Int, val name: String)
Here id identifies the item and name is its content. If an item keeps its id but its name changes, it is
reported as updated. If an id appears only in the new list it is inserted, if it appears only in the old list it
is removed, and if it changes position it is moved.
2. Write a regular adapter
The adapter is an ordinary RecyclerView.Adapter. Its only requirement is that its data can be replaced, here
through a mutable items property.
class ItemAdapter(var items: List<Item>) : RecyclerView.Adapter<ItemViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder =
ItemViewHolder(ItemView(parent.context))
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
holder.view.itemName = items[position].name
}
override fun getItemCount(): Int = items.size
}
class ItemViewHolder(val view: ItemView) : RecyclerView.ViewHolder(view)
3. Create the manager
RecyclerViewManager<VH, T> takes three arguments:
| Parameter | Type | Purpose |
|---|---|---|
|
|
The adapter that receives the notifications. |
|
|
Returns |
|
|
Returns |
Both comparators are single-method Java interfaces from hermes, so in Kotlin they can be passed as lambdas:
private val adapter = ItemAdapter(emptyList())
private val manager = RecyclerViewManager<ItemViewHolder, Item>(
adapter,
// ItemComparator: are both items the same entity?
{ item1, item2 -> item1.id == item2.id },
// ItemContentComparator: is the content of the same entity unchanged?
{ item1, item2 -> item1.name == item2.name }
)
Or, if you prefer reusable named implementations:
import com.irurueta.hermes.ItemComparator
import com.irurueta.hermes.ItemContentComparator
// Comparators can also be declared as reusable objects
object ItemIdentity : ItemComparator<Item> {
override fun equals(item1: Item, item2: Item) = item1.id == item2.id
}
object ItemContent : ItemContentComparator<Item> {
override fun equalContent(item1: Item, item2: Item) = item1 == item2
}
val manager = RecyclerViewManager<ItemViewHolder, Item>(adapter, ItemIdentity, ItemContent)
4. Notify changes
Each time the data changes, do these two steps in this order:
-
Give the new list to the adapter, so
getItemCount()already returns the new size. -
Call
notifyChanges(oldItems, newItems), passing the old list first.
fun updateItems(newItems: List<Item>) {
val oldItems = adapter.items
// 1. Hand the new data to the adapter first: getItemCount() must already
// return the size of the new list.
adapter.items = newItems
// 2. Compute the differences and notify the adapter (old list first!).
manager.notifyChanges(oldItems, newItems)
}
The argument order is notifyChanges(oldItems, newItems). Swapping the lists, or updating the adapter
after the call, makes RecyclerView see notifications that don’t match the adapter’s data. That leads to wrong
animations or an IndexOutOfBoundsException / "Inconsistency detected" crash.
|
Call notifyChanges on the main thread, like any other adapter notification. The detection runs synchronously on the
calling thread.
What is notified
| Detected change | Adapter call |
|---|---|
Item only in the new list |
|
Item only in the old list |
|
Same item, different content |
|
Same item, different position |
|
New list is empty ( |
|
Positions are sequential: each one refers to the list as it looks after the previous notifications have been applied,
which is how RecyclerView processes a series of notifications.
Reacting to a Flow or LiveData
A common pattern is to collect a list exposed by a view model and forward each emission to the manager. The adapter’s current list is always the "old" list:
class ItemsActivity : ComponentActivity() {
private val viewModel: ItemsViewModel by viewModels()
private val adapter = ItemAdapter(emptyList())
private val manager = RecyclerViewManager<ItemViewHolder, Item>(
adapter,
{ a, b -> a.id == b.id },
{ a, b -> a.name == b.name }
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_items)
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
// StateFlow<List<Item>> exposed by the view model; collected on the main thread
viewModel.items.collect { newItems ->
val oldItems = adapter.items
adapter.items = newItems
manager.notifyChanges(oldItems, newItems)
}
}
}
}
}
The same idea applies to LiveData.observe: inside the observer, read adapter.items, assign the new value and call
notifyChanges.
Inspecting changes without notifying
The underlying detector is exposed as the detector property, so you can compute the changes yourself, for example
for logging or analytics. Note that detectChanges takes the new list first:
import com.irurueta.hermes.InsertedListItemChange
import com.irurueta.hermes.MovedListItemChange
import com.irurueta.hermes.RemovedListItemChange
import com.irurueta.hermes.UpdatedListItemChange
// Note the argument order of the underlying detector: new items first
val changes = manager.detector.detectChanges(newItems, oldItems)
for (change in changes) {
when (change) {
is InsertedListItemChange<*> -> Log.d(TAG, "inserted at ${change.newPosition}")
is RemovedListItemChange<*> -> Log.d(TAG, "removed from ${change.oldPosition}")
is UpdatedListItemChange<*> -> Log.d(TAG, "updated at ${change.position}")
is MovedListItemChange<*> ->
Log.d(TAG, "moved from ${change.oldPosition} to ${change.newPosition}")
}
}
Tips
-
Keep the identity comparator stable. Comparing whole objects (
item1 == item2) as the identity rule turns every edit into a removal plus an insertion instead of an update. -
Make the content comparator cheap. It is called for items that are present in both lists.
-
Ids should be unique within a list. Duplicate identities make it ambiguous which item moved.
-
The manager logs each notification at
DEBUGlevel with theRecyclerViewManagertag, which helps when diagnosing unexpected animations (adb logcat -s RecyclerViewManager).
Next: Sample app.