我正在研究AsyncListDiffer
在Android中的实现,并且停留在一个地方。
mReadOnlyList
的用途是什么?
public class AsyncListDiffer<T> {
private List<T> mList;
@NonNull
private List<T> mReadOnlyList = Collections.emptyList();
@NonNull
public List<T> getCurrentList() {
return mReadOnlyList;
}
public void submitList(final List<T> newList) {
...
if (newList == null) {
mList = null;
mReadOnlyList = Collections.emptyList();
return;
}
if (mList == null) {
mList = newList;
mReadOnlyList = Collections.unmodifiableList(newList);
return;
}
}
private void latchList(@NonNull List<T> newList, @NonNull DiffUtil.DiffResult diffResult) {
mList = newList;
mReadOnlyList = Collections.unmodifiableList(newList);
diffResult.dispatchUpdatesTo(mUpdateCallback);
}
}
getCurrentList()
仅可访问
public abstract class ListAdapter<T, VH extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<VH> {
...
private final AsyncListDiffer<T> mHelper;
protected T getItem(int position) {
return mHelper.getCurrentList().get(position);
}
public int getItemCount() {
return mHelper.getCurrentList().size();
}
}
为什么他们不简单地在getItem(int position)
中创建诸如getItemCount()
和AsyncListDiffer
之类的2个方法而不创建mReadOnlyList
?
因为我看到newList
发生了变化,所以mReadOnlyList
也发生了变化
Collections.unmodifiableList and defensive copy