small improvement in StateFlowBasedRecyclerViewAdapter

This commit is contained in:
InsanusMokrassar 2021-06-17 13:45:19 +06:00
parent e715772dbf
commit 6d999be590

View File

@ -15,16 +15,29 @@ abstract class StateFlowBasedRecyclerViewAdapter<T>(
init { init {
dataState.onEach { dataState.onEach {
val diff = Diff(data, it) val diffForRemoves = Diff(data, it)
val removedIndexes = diffForRemoves.removed.map { it.index }
val leftRemove = removedIndexes.toMutableList()
data = data.filterIndexed { i, _ ->
if (i in leftRemove) {
leftRemove.remove(i)
true
} else {
false
}
}
withContext(Dispatchers.Main) {
removedIndexes.sortedDescending().forEach {
notifyItemRemoved(it)
}
}
val diffAddsAndReplaces = Diff(data, it)
data = it data = it
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
diff.removed.forEach { diffAddsAndReplaces.replaced.forEach { (from, to) ->
notifyItemRemoved(it.index)
}
diff.replaced.forEach { (from, to) ->
notifyItemMoved(from.index, to.index) notifyItemMoved(from.index, to.index)
} }
diff.added.forEach { diffAddsAndReplaces.added.forEach {
notifyItemInserted(it.index) notifyItemInserted(it.index)
} }
} }