RecycleView的notifyDataSetChanged()之坑

       前几天帮同事排查一个调用notifyDataSetChanged()未刷新的bug。刚开始在网上查,几乎都是说,如果数据源变了,adapter访问的还是老的数据源,所以刷新无效。我看了下同事代码确实是数据源地址变了。解决办法是adapter里new一个List,然后每次addAll新的数据,保证地址不变。
       然后我就去看源码,首先我们从setAdapter()开始看:

   /**
     * Set a new adapter to provide child views on demand.
     * 

* When adapter is changed, all existing views are recycled back to the pool. If the pool has * only one adapter, it will be cleared. * * @param adapter The new adapter to set, or null to set no adapter. * @see #swapAdapter(Adapter, boolean) */ public void setAdapter(Adapter adapter) { // bail out if layout is frozen setLayoutFrozen(false); setAdapterInternal(adapter, false, true); processDataSetCompletelyChanged(false); requestLayout(); }

 /**
     * Replaces the current adapter with the new one and triggers listeners.
     * @param adapter The new adapter
     * @param compatibleWithPrevious If true, the new adapter is using the same View Holders and
     *                               item types with the current adapter (helps us avoid cache
     *                               invalidation).
     * @param removeAndRecycleViews  If true, we'll remove and recycle all existing views. If
     *                               compatibleWithPrevious is false, this parameter is ignored.
     */
    private void setAdapterInternal(Adapter adapter, boolean compatibleWithPrevious,
            boolean removeAndRecycleViews) {
//注意这个mObserver,类名是RecyclerViewDataObserver,即数据源变化的观察者/订阅者,在这里先给原来的adapter注销了这个观察者,再给新的adapter注册了这个观察者
        if (mAdapter != null) {
            mAdapter.unregisterAdapterDataObserver(mObserver);
            mAdapter.onDetachedFromRecyclerView(this);
        }
        if (!compatibleWithPrevious || removeAndRecycleViews) {
            removeAndRecycleViews();
        }
        mAdapterHelper.reset();
        final Adapter oldAdapter = mAdapter;
        mAdapter = adapter;
        if (adapter != null) {
            //追踪这行代码内部实现
            adapter.registerAdapterDataObserver(mObserver);
            adapter.onAttachedToRecyclerView(this);
        }
        if (mLayout != null) {
            mLayout.onAdapterChanged(oldAdapter, mAdapter);
        }
        mRecycler.onAdapterChanged(oldAdapter, mAdapter, compatibleWithPrevious);
        mState.mStructureChanged = true;
    }
public void registerAdapterDataObserver(@NonNull AdapterDataObserver observer) {
           //mObservable出现了,这个就是被观察/被订阅的主题,类名是AdapterDataObservable,被定义在RecycleView.Adapter类里,
           //这个对象在**运行时**就已经分配好了内存空间,使用final 修饰。
            mObservable.registerObserver(observer);
        }
//当我们调用notifyDataSetChanged()方法时,mObservable将会去通知所有的观察者数据变化了
 public final void notifyDataSetChanged() {
            //追踪这行代码内部实现
            mObservable.notifyChanged();
        }
 public void notifyChanged() {
            // since onChanged() is implemented by the app, it could do anything, including
            // removing itself from {@link mObservers} - and that could cause problems if
            // an iterator is used on the ArrayList {@link mObservers}.
            // to avoid such problems, just march thru the list in the reverse order.
            for (int i = mObservers.size() - 1; i >= 0; i--) {
                //继续追踪
                mObservers.get(i).onChanged();
            }
        }
//可以看到这里就是对数据源变化做出的逻辑处理
 @Override
        public void onChanged() {
            assertNotInLayoutOrScroll(null);
            mState.mStructureChanged = true;

            processDataSetCompletelyChanged(true);
            if (!mAdapterHelper.hasPendingUpdates()) {
                requestLayout();
            }
        }

       我把这段源码反复看了好几遍,实在是没想通adapter内部没有任何地方获取了List对象的地址啊?我们在继承Adapter的时候重写的那几个方法,也根本没把List地址抛给Adapter,数据渲染都是Adapter通过onBindViewHolder()回调让我们自己获取数据渲染的。当List数据有变动的时候,我们调notifyDataSetChanged(),就是走我们刚刚看过的这几段代码的逻辑。但是大多数人都说保证List地址不变动就可解决应该是已经实践可行的方式了,只是我不懂这其中的缘由,如果有了解的朋友,麻烦在下方留言告知我,十分感谢!
       说一下我的解决办法吧。我们看onChanged()的实现里,有一段这样的代码:

if (!mAdapterHelper.hasPendingUpdates()) {
                requestLayout();
            }

我怀疑是因为没有走进这个if逻辑里,所以没有执行 requestLayout();
来刷新布局。于是,我追踪查看mAdapterHelper.hasPendingUpdates()的实现:

boolean hasPendingUpdates() {
        return mPendingUpdates.size() > 0;
    }

继续查看mPendingUpdates这个变量在何时才会改变size,在这里,我们就Ctrl+F直接搜索mPendingUpdates.add,查看:

 /**
     * @return True if updates should be processed.
     */
    boolean onItemRangeChanged(int positionStart, int itemCount, Object payload) {
        if (itemCount < 1) {
            return false;
        }
        mPendingUpdates.add(obtainUpdateOp(UpdateOp.UPDATE, positionStart, itemCount, payload));
        mExistingUpdateTypes |= UpdateOp.UPDATE;
        return mPendingUpdates.size() == 1;
    }

    /**
     * @return True if updates should be processed.
     */
    boolean onItemRangeInserted(int positionStart, int itemCount) {
        if (itemCount < 1) {
            return false;
        }
        mPendingUpdates.add(obtainUpdateOp(UpdateOp.ADD, positionStart, itemCount, null));
        mExistingUpdateTypes |= UpdateOp.ADD;
        return mPendingUpdates.size() == 1;
    }

    /**
     * @return True if updates should be processed.
     */
    boolean onItemRangeRemoved(int positionStart, int itemCount) {
        if (itemCount < 1) {
            return false;
        }
        mPendingUpdates.add(obtainUpdateOp(UpdateOp.REMOVE, positionStart, itemCount, null));
        mExistingUpdateTypes |= UpdateOp.REMOVE;
        return mPendingUpdates.size() == 1;
    }

    /**
     * @return True if updates should be processed.
     */
    boolean onItemRangeMoved(int from, int to, int itemCount) {
        if (from == to) {
            return false; // no-op
        }
        if (itemCount != 1) {
            throw new IllegalArgumentException("Moving more than 1 item is not supported yet");
        }
        mPendingUpdates.add(obtainUpdateOp(UpdateOp.MOVE, from, to, null));
        mExistingUpdateTypes |= UpdateOp.MOVE;
        return mPendingUpdates.size() == 1;
    }

只有在这4个方法里才会进行add操作。随便选中一个,查看这些方法的调用之处,我就不贴代码了,在RecyclerViewDataObserver类里调用了,继续查看谁调用了RecyclerViewDataObserver的这几个方法。反正照这个思路一直找下去,最后你就会发现当我们调用adapter的notifyItemChanged()/notifyItemRangeChanged()/notifyItemInserted()/notifyItemMoved()等等这些方法的时候,才会改变mPendingUpdates的size,从而在走onChange()的时候才会刷新布局。

       DuangDuangDuang!!!解决办法来了,在这种情况下,调用adapter.notifyItemChanged(int position, Object payload) 第二个参数为null或者"full"时是刷新全部,否则就是局部刷新,所以参数可以传(-1,null),问题就解决了!

你可能感兴趣的:(RecycleView的notifyDataSetChanged()之坑)