在RecyclerView中實現(xiàn)定點刷新

本篇文章已授權微信公眾號 guolin_blog (郭霖)獨家發(fā)布

寫在前面

近期,在筆者開源的BindingListAdapter庫中出現(xiàn)了這樣的一個Issue。

這其實是一個在列表中比較常見的問題,在沒有找到比較好的解決辦法之前,確實都是通過整項刷新notifyDataChanged來保證數(shù)據(jù)顯示的正確性。到后來的notifyItemChanged和更佳的DiffUtil,說明開發(fā)者們一直都在想辦法來解決并優(yōu)化它。

但其實如果你使用DataBinding,做這個局部刷新或者說是定點刷新,就很簡單了,這可能是大多數(shù)使用DataBinding的開發(fā)者并不知道的技巧。

巧用ObservableFiled

可以先看看實際的效果

關鍵點就在于不要直接綁定具體的值到xml中,應先使用ObservableField包裹一層。

class ItemViewModel constructor( val data:String){
    //not
    //val count = data
    //val liked = false
    
    //should
    val count = ObservableField<String>(data)
    val liked = ObservableBoolean()
}

//partial_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
    <data>
        <variable
            name="item"
            type="io.ditclear.app.partial.PartialItemViewModel" />

        <variable
            name="presenter"
            type="io.ditclear.bindingadapterx.ItemClickPresenter" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:onClick="@{(v)->presenter.onItemClick(v,item)}"
        >
        <TextView
            android:text="@{item.count}" />
        <ImageView
            android:src="@{item.liked?@drawable/ic_action_liked:@drawable/ic_action_unlike}"/>
    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

當UI需要改變時,改變ItemViewModel的數(shù)據(jù)即可。

//activity

override fun onItemClick(v: View, item: PartialItemViewModel) {
    item.toggle()
}

// ItemViewModle
 fun toggle(){
        liked.set(!liked.get())

        count.set("$data ${if (liked.get()) "liked" else ""}")
    }

至于為什么?這就要說到DataBinding更新UI的原理了。

DataBinding更新UI原理

當我們在項目中運用DataBinding,并將xml文件轉(zhuǎn)換為DataBinding形式之后。經(jīng)過編譯build,會生成相應的binding文件,比如partial_list_item.xml就會生成對于的PartialListItemBinding文件,這是一個抽象類,還會有一個PartialListItemBindingImpl實現(xiàn)類實現(xiàn)具體的渲染UI的方法executeBindings。

當數(shù)據(jù)有改變的時候,就會重新調(diào)用executeBindings方法,更新UI,那怎么做到的呢?

我們先來看PartialListItemBinding的構造方法.

public abstract class PartialListItemBinding extends ViewDataBinding {
  @NonNull
  public final ImageView imageView;

  @Bindable
  protected PartialItemViewModel mItem;

  @Bindable
  protected ItemClickPresenter mPresenter;

  protected PartialListItemBinding(DataBindingComponent _bindingComponent, View _root,
      int _localFieldCount, ImageView imageView) {
      //調(diào)用父類的構造方法
    super(_bindingComponent, _root, _localFieldCount);
    this.imageView = imageView;
  }
  //... 
 }

調(diào)用了父類ViewDataBinding的構造方法,并傳入了三個參數(shù),這里看第三個參數(shù)_localFieldCount,它代表xml中存在幾個ObservableField形式的數(shù)據(jù),繼續(xù)追蹤.

protected ViewDataBinding(DataBindingComponent bindingComponent, View root, int localFieldCount) {
    this.mBindingComponent = bindingComponent;
    //考點1
    this.mLocalFieldObservers = new ViewDataBinding.WeakListener[localFieldCount];
    this.mRoot = root;
    if (Looper.myLooper() == null) {
        throw new IllegalStateException("DataBinding must be created in view's UI Thread");
    } else {
        if (USE_CHOREOGRAPHER) {
            //考點2
            this.mChoreographer = Choreographer.getInstance();
            this.mFrameCallback = new FrameCallback() {
                public void doFrame(long frameTimeNanos) {
                    ViewDataBinding.this.mRebindRunnable.run();
                }
            };
        } else {
            this.mFrameCallback = null;
            this.mUIThreadHandler = new Handler(Looper.myLooper());
        }

    }
}

通過《觀察》,發(fā)現(xiàn)其根據(jù)localFieldCount初始化了一個WeakListener數(shù)組,名為mLocalFieldObservers。另一個重點是初始化了一個mFrameCallback,在回調(diào)中執(zhí)行了mRebindRunnable.run。

當生成的PartialListItemBindingImpl對象調(diào)用executeBindings方法時,通過updateRegistration會對mLocalFieldObservers數(shù)組中的內(nèi)容進行賦值。

隨之生成的是相應的WeakPropertyListener,來看看它的定義。

private static class WeakPropertyListener extends Observable.OnPropertyChangedCallback
        implements ObservableReference<Observable> {
    final WeakListener<Observable> mListener;

    public WeakPropertyListener(ViewDataBinding binder, int localFieldId) {
        mListener = new WeakListener<Observable>(binder, localFieldId, this);
    }

    //...
    @Override
    public void onPropertyChanged(Observable sender, int propertyId) {
        ViewDataBinding binder = mListener.getBinder();
        if (binder == null) {
            return;
        }
        Observable obj = mListener.getTarget();
        if (obj != sender) {
            return; // notification from the wrong object?
        }
        //劃重點
        binder.handleFieldChange(mListener.mLocalFieldId, sender, propertyId);
    }
}

ObservableField的值有改變的時候,onPropertyChanged會被調(diào)用,然后就會回調(diào)binder(即binding對象)的handleFieldChange方法,繼續(xù)觀察。

private void handleFieldChange(int mLocalFieldId, Object object, int fieldId) {
    if (!this.mInLiveDataRegisterObserver) {
        boolean result = this.onFieldChange(mLocalFieldId, object, fieldId);
        if (result) {
            this.requestRebind();
        }

    }
}

如果值有改變 ,result為true,接著requestRebind方法被執(zhí)行。

protected void requestRebind() {
    if (this.mContainingBinding != null) {
        this.mContainingBinding.requestRebind();
    } else {
        synchronized(this) {
            if (this.mPendingRebind) {
                return;
            }

            this.mPendingRebind = true;
        }

        if (this.mLifecycleOwner != null) {
            State state = this.mLifecycleOwner.getLifecycle().getCurrentState();
            if (!state.isAtLeast(State.STARTED)) {
                return;
            }
        }
        //劃重點
        if (USE_CHOREOGRAPHER) { // SDK_INT >= 16
            this.mChoreographer.postFrameCallback(this.mFrameCallback);
        } else {
            this.mUIThreadHandler.post(this.mRebindRunnable);
        }
    }

}

在上述代碼最后,可以看到sdk版本16以上會執(zhí)行

this.mChoreographer.postFrameCallback(this.mFrameCallback);,16以下則是通過Handler

關于postFrameCallBack,給的注釋是Posts a frame callback to run on the next frame.,簡單理解就是發(fā)生在下一幀即16ms之后的回調(diào)。

關于Choreographer,推薦閱讀 Choreographer 解析

但不管如何,最終都是調(diào)用mRebindRunnable.run,來看看對它的定義。

/**
 * Runnable executed on animation heartbeat to rebind the dirty Views.
 */
private final Runnable mRebindRunnable = new Runnable() {
    @Override
    public void run() {
        synchronized (this) {
            mPendingRebind = false;
        }
        processReferenceQueue();

        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            // Nested so that we don't get a lint warning in IntelliJ
            if (!mRoot.isAttachedToWindow()) {
                // Don't execute the pending bindings until the View
                // is attached again.
                mRoot.removeOnAttachStateChangeListener(ROOT_REATTACHED_LISTENER);
                mRoot.addOnAttachStateChangeListener(ROOT_REATTACHED_LISTENER);
                return;
            }
        }
        //劃重點
        executePendingBindings();
    }
};

其實就是在下一幀的時候再執(zhí)行了一次executePendingBindings方法,到這里,DataBinding更新UI的邏輯我們也就全部打通了。

寫在最后

筆者已經(jīng)使用了DataBinding好幾年的時間,深切的體會到了它對于開發(fā)效率的提升,決不下于Kotlin,用好了它就是劍客最鋒利的寶劍,削鐵如泥,用不好便自損八百。為此,上一年我專門寫了一篇DataBinding實用指南講了講自己的使用經(jīng)驗,同時開源了運用DataBinding來簡化RecyclerView適配器的BindingListAdapter,希望更多的開發(fā)者喜歡它。

GitHub示例:https://github.com/ditclear/BindingListAdapter

參考資料

深入Android databinding的使用和原理分析

Choreographer 解析

==================== 分割線 ======================

如果你想了解更多關于MVVM、Flutter、響應式編程方面的知識,歡迎關注我。

你可以在以下地方找到我:

簡書:http://www.itdecent.cn/u/117f1cf0c556

掘金:https://juejin.im/user/582d601d2e958a0069bbe687

Github: https://github.com/ditclear

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容