1

I am looking at the implementation of AsyncListDiffer in Android and I am stuck at one point.
How is the mReadOnlyList is used for?

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);
    }
}

And getCurrentList() only access in

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();
    }
}

Why they don't simple create 2 methods like getItem(int position) and getItemCount() in AsyncListDiffer without create a mReadOnlyList?
Because I see when newList change, mReadOnlyList also change Collections.unmodifiableList and defensive copy

Linh
  • 57,942
  • 23
  • 262
  • 279

0 Answers0