Skip to content

Commit

Permalink
Fix invalid view holder adapter position exception
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-megh-l committed Jan 23, 2024
1 parent d62c935 commit c1039b9
Showing 1 changed file with 15 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,13 @@ class ComposeRecyclerViewAdapter :
fun getItemType(position: Int): Int
}

private var itemList: MutableList<Any> = mutableListOf()

var totalItems: Int = 0
set(value) {
if (field == value) return
field = value
if (field == -1) {
notifyItemInserted(0)
} else {
notifyItemChanged(0)
}
notifyItemRangeChange(value)
}

var itemBuilder: (@Composable (index: Int) -> Unit)? =
Expand Down Expand Up @@ -80,4 +78,16 @@ class ComposeRecyclerViewAdapter :
this.itemTypeBuilder = it
}
}

private fun notifyItemRangeChange(newSize: Int) {
val oldSize = itemList.size
if (newSize < oldSize) {
itemList = itemList.subList(0, newSize)
notifyItemRangeRemoved(newSize, oldSize - newSize)
} else if (newSize > oldSize) {
val list = MutableList(newSize - oldSize) { Any() }
itemList = (itemList + list).toMutableList()
notifyItemRangeInserted(oldSize, newSize - oldSize)
}
}
}

0 comments on commit c1039b9

Please sign in to comment.