Skip to content

Commit

Permalink
Use DiffUtil to calculate difference for LogsAdapter
Browse files Browse the repository at this point in the history
LogsFragment was lagging my Android Interop on my System.
This is because `notifyDataSetChanged` is used,
 it is computationally intensive and should never be used.

Implementation of a quick DiffUtil calculator solves this.

In response to work done:
#5482
  • Loading branch information
Doomsdayrs authored and westnordost committed Feb 15, 2024
1 parent 2ff49c9 commit 04c473c
Showing 1 changed file with 25 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package de.westnordost.streetcomplete.screens.about
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.widget.TextViewCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import de.westnordost.streetcomplete.data.logs.LogMessage
import de.westnordost.streetcomplete.databinding.RowLogMessageBinding
Expand All @@ -12,7 +13,8 @@ import kotlinx.datetime.toLocalDateTime

class LogsAdapter : RecyclerView.Adapter<LogsAdapter.ViewHolder>() {

class ViewHolder(private val binding: RowLogMessageBinding) : RecyclerView.ViewHolder(binding.root) {
class ViewHolder(private val binding: RowLogMessageBinding) :
RecyclerView.ViewHolder(binding.root) {
fun onBind(with: LogMessage) {
binding.messageTextView.text = with.toString()

Expand All @@ -29,8 +31,29 @@ class LogsAdapter : RecyclerView.Adapter<LogsAdapter.ViewHolder>() {
var messages: List<LogMessage>
get() = _messages
set(value) {
val result = DiffUtil.calculateDiff(
object : DiffUtil.Callback() {
override fun getOldListSize(): Int =
_messages.size

override fun getNewListSize(): Int =
value.size

override fun areItemsTheSame(
oldItemPosition: Int,
newItemPosition: Int,
): Boolean =
_messages[oldItemPosition].timestamp == value[newItemPosition].timestamp

// contents never change
override fun areContentsTheSame(
oldItemPosition: Int,
newItemPosition: Int,
): Boolean = areItemsTheSame(oldItemPosition, newItemPosition)
}
)
_messages = value.toMutableList()
notifyDataSetChanged()
result.dispatchUpdatesTo(this)
}

private var _messages: MutableList<LogMessage> = mutableListOf()
Expand Down

0 comments on commit 04c473c

Please sign in to comment.