반응형

간단하게 알아보자!

val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Item>() {
	override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
    		return oldItem == newItem
	}

	override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
		return oldItem == newItem
	}
}

DiffUtil을 이용해서 리사이클러뷰를 구현했는데, 처음에는 위와같이 구현했다. 아무 문제 없어보이나 areItemsTheSame에서는 고유한 아이디 값을 비교해주는 것이 좋다는 리뷰를 받았다. 

 

그렇다면 여기서 areItemsTheSame 함수와 areContentsTheSame함수가 하는 일이 무엇인지 알아보자!

각 함수의 Returns 부분만 살펴보면 된다.

먼저 areItemsTheSame 함수는 Returns: Ture if the two items represent the same object or false if they are different. 라고 되어 있고, areContentsTheSame 함수는 Returns True if the contents of the items are the same or false if they are different.라고 되어 있다. 즉, areItemsTheSame 함수는 같은 객체인지 확인하는 것이고, areContentsTheSame 함수는 아이템들의 값이 같은지 확인하는 것이다. 

 

그러므로 ==을 통해 비교하는 것은 데이터 클래스의 프로퍼티가 같은지 비교하는 것이기 때문에 areItemsTheSame에서는 ==을 통해 비교하는 것이 알맞지 않다. 그러므로 areItemsTheSame에서는 ===을 통해 실제 같은 객체인지 비교해주도록 하자.

반응형

+ Recent posts