Android Architecture Component之LiveData

前言

系列文章

一、liveData是什么?

1.介紹

  • LiveData是一個(gè)數(shù)據(jù)持有者類,他持有一個(gè)允許被觀察的值,不同于普通的被觀察者,liveData遵從應(yīng)用程序的生命周期,被注冊(cè)的觀察者都要遵循其生命周期。
  • 如果觀察者的生命周期處于started或者resumed狀態(tài)的時(shí)候,liveData認(rèn)為觀察者處于活動(dòng)狀態(tài)。
    LiveData只通知處于活躍狀態(tài)的observer,不活躍的不通知其改變。
  1. 優(yōu)點(diǎn)
  • 沒有內(nèi)存泄漏的風(fēng)險(xiǎn),當(dāng)頁(yè)面銷毀的時(shí)候,他們會(huì)自動(dòng)被移除,不會(huì)導(dǎo)致內(nèi)存溢出
  • 不會(huì)因?yàn)閍ctivity的不可見導(dǎo)致crash。
    • 當(dāng)Activity不可見的時(shí)候,即使有數(shù)據(jù)發(fā)生改變,LiveData也不同通知觀察者,因?yàn)榇帕Φ挠^察者的生命周期處于Started或者Resumed狀態(tài)
  • 配置的改變。
    • 當(dāng)前的Activity配置發(fā)生改變(如屏幕方向,導(dǎo)致生命周期重新走了一遍,但是觀察者們會(huì)恢復(fù)到變化前的數(shù)據(jù)。
  • 資源共享
    • 我們的LiveData,只要連接系統(tǒng)服務(wù)一次就能支持所有的觀察者。
  • 不在手動(dòng)處理生命周期
    • 生命周期組件,只需要在觀察數(shù)據(jù)的時(shí)候觀察數(shù)據(jù)即可,不需要理會(huì)生命周期,這一切就交給類liveData.
  • 總是能獲取最新的數(shù)據(jù)
    • 當(dāng)Activity從后臺(tái)進(jìn)入前臺(tái)的時(shí)候總共能夠獲取最新的數(shù)據(jù)。
二、用法簡(jiǎn)介
  • 添加依賴
    compile "android.arch.lifecycle:runtime:1.0.3"
    compile "android.arch.lifecycle:extensions:1.0.0-rc1"
    annotationProcessor "android.arch.lifecycle:compiler:1.0.0-rc1"
    
  • 創(chuàng)建一個(gè)LiveData的實(shí)例來保存特定類型的數(shù)據(jù)。 這通常在ViewModel類中完成。
    public class MainViewModel extends AndroidViewModel {
    private int i=10;
    
    private MutableLiveData<Student> studentMutableLiveData =new MutableLiveData<>();
    
    public MainViewModel(Application application) {
        super(application);
    }
    
    
    public void changeName(Student student) {
    
        student.setAge(i++);
        studentMutableLiveData.setValue(student);
    
    }
    
    public MutableLiveData<Student> getStudentMutableLiveData() {
        return studentMutableLiveData;
    }
    }
    
    MutableLiveData類公開公開setValue(T)和postValue(T)方法,如果需要編輯存儲(chǔ)在LiveData對(duì)象中的值,則必須使用這些方法。 通常在ViewModel使用MutableLiveData ,然后ViewModel僅向觀察者公開不可變的LiveData對(duì)象。
  • 在Activity中
    ViewModelProvider of = ViewModelProviders.of(this);
       mainViewModel = of.get(MainViewModel.class);
       mainViewModel.getStudentMutableLiveData().observe(this, new Observer<Student>() {
           @Override
           public void onChanged(@Nullable Student student) {
    
    
           }
       });
       findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
    
               mainViewModel.changeName(mstudent);
    
           }
       });
    
    每次點(diǎn)擊之后都會(huì)調(diào)用LiveData的setValue()方法,注冊(cè)的觀察者在onChanged()方法中就會(huì)收到更新后的我們觀察的數(shù)據(jù)student.
三、源碼分析

我們主要從三個(gè)方面講解:怎么添加觀察者?什么時(shí)候通知調(diào)用觀察者,怎么移除觀察者?怎么判定是liveData是活動(dòng)活動(dòng)狀態(tài)?

  1. 怎么添加觀察者?
  • 上面的列子用到了MutableLiveData,看下他的源碼
    public class MutableLiveData<T> extends LiveData<T> {
    @Override
    public void postValue(T value) {
        super.postValue(value);
    }
    
    @Override
    public void setValue(T value) {
        super.setValue(value);
    }
    }
    
    很簡(jiǎn)單,繼承了LiveData,提供了兩個(gè)修改我們要觀察數(shù)據(jù)的值。

    注意: 您必須調(diào)用setValue(T)方法來更新主線程中的LiveData對(duì)象。如果代碼在工作線程中執(zhí)行,則可以使用postValue(T)方法更新LiveData對(duì)象。

  • 從上面的列子中我們看到了MutableLiveData調(diào)用了observe()方法,這個(gè)方法是干什么用的呢?observer()繼承于LiveData,所以我們看下LiveData的Observer()
      @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        LifecycleBoundObserver existing = mObservers.putIfAbsent(observer, wrapper);
        if (existing != null && existing.owner != wrapper.owner) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        owner.getLifecycle().addObserver(wrapper);
    }
    
    • LifecycleOwner在上面的列子中我們傳入的是this,上篇我們說Lifecycle-Aware Components的時(shí)候我們知道activity實(shí)現(xiàn)了LifecycleOwner(繼承了class SupportActivity extends Activity implements LifecycleOwner )有個(gè)方法getLifecycle()返回了一個(gè)LifecycleRegistry的被觀察者,它的主要作用是組件生命周期通知注冊(cè)的觀察者,做出改變。

    • 方法進(jìn)來之后,首先獲取LifecycleRegistry中當(dāng)前組件的狀態(tài),如果處于destoryed,就什么也不做。

    • 如果不是destroyed就把我們的觀察者封裝成了LifecycleBoundObserver(),

    • 然后判斷我們LiveData中的觀察者mObservers集合中有咩有,沒有的話就放入,有的話就返回空。

    • 如果沒有的話也放入我們Activity組件中LifecycleRegistry中觀察者集合中(這里面的觀察者很雜,有觀察數(shù)據(jù)的觀察者(屬于liveData),也有我們上篇講到到用注解自定義的觀察者(處理與生命周期有關(guān)事件的))。

  1. 什么時(shí)候通知觀察者?
  • 有人也可能會(huì)問為什么我們要把liveData中的觀察者注冊(cè)到LifecycleRegistry的handleLifecycleEvent()中,它自己不是有自己的觀察者集合嗎?

    這是因?yàn)樵谏掀覀儗⒔M件的生命周期事件分發(fā)的時(shí)候講到過通過LifecycleRegistry的handleLifecycleEvent()方法,而它被通過Activity中的ReportFragment的各個(gè)生命周期方法調(diào)用,所以我們要把我們的觀察者注冊(cè)到LifecycleRegistry,交由它去負(fù)責(zé)生命周期事件分發(fā)給我們的觀察者。

  • 注冊(cè)到LifecycleRegistry中的時(shí)候會(huì)被封裝成ObserverWithState觀察者,有生命周期事件的時(shí)候會(huì)調(diào)用ObserverWithState的dispatchEvent()

     ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }
     void dispatchEvent(LifecycleOwner owner, Event event) {
                State newState = getStateAfter(event);
                mState = min(mState, newState);
                mLifecycleObserver.onStateChanged(owner, event);
                mState = newState;
            }
    

    其中傳入的LifecycleObserver就是我們上面講的LifecycleBoundObserver,我們看到代碼中的dispatchEvent(),會(huì)調(diào)用onStateChanged,他怎么寫的呢?

    @Override
            public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
                if (owner.getLifecycle().getCurrentState() == DESTROYED就一處,不是就通知改變) {
                    removeObserver(observer);
                    return;
                }
                // immediately set active state, so we'd never dispatch anything to inactive
                // owner
                activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState()));
            }
    

    若果當(dāng)前的LifecycleRegistry的狀態(tài)是DESTROYED就移除我們的觀察者,這就知道什么時(shí)候移除,我們也就不需要擔(dān)心內(nèi)存泄漏的風(fēng)險(xiǎn)。不是就通知改變,怎么通知觀察者的呢?我們看下activeStateChanged,傳入的參數(shù)我們后面會(huì)提到,先看下它的源碼。

     if (active) {
                dispatchingValue(this);
            }
    

    如果處于活動(dòng)狀態(tài)就調(diào)用dispatchingValue()

    for (Iterator<Map.Entry<Observer<T>, LifecycleBoundObserver>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    for (Iterator<Map.Entry<Observer<T>, LifecycleBoundObserver>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
    

    在這里遍歷liveData存放觀察者的集合,然后considerNotify().看下源碼

    observer.observer.onChanged()((T) mData);
    

    onChanged()方法就是我們?cè)谟梅ㄖ凶罱K回調(diào)的方法。

    我們總結(jié)一下過程:

    • liveData的observer(),把我們的觀察者封裝成了LifecycleBoundObserver,這個(gè)是liveData專用的觀察者。
    • 添加到LiveData的觀察者集合和Activity中的LifecycleRegistry的集合(負(fù)責(zé)生命周期分發(fā),和獲取當(dāng)前activit狀態(tài))
    • 當(dāng)Activity狀態(tài)發(fā)生改變,就會(huì)通知我們的了LifecycleBoundObserver,同時(shí)調(diào)用它的onStateChanged()
    • 然后在調(diào)用activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState()));
    • 然后遍歷liveData的觀察集合最后知道調(diào)用observer.observer.onChanged()((T) mData);
  1. 怎么判斷l(xiāng)iveData是出于活躍狀態(tài)?
    在文章的開頭部分我們提到:

    如果觀察者的生命周期處于started或者resumed狀態(tài)的時(shí)候,liveData認(rèn)為觀察者處于活動(dòng)狀態(tài)。

    代碼中怎么體現(xiàn)出來的呢?

  • 在上面的帶面中我們分析到了
    activeStateChanged(
    isActiveState(owner.getLifecycle().getCurrentState()));
    
    其中有個(gè)關(guān)鍵方法就是
    isActiveState(owner.getLifecycle().getCurrentState())
    
    看下它的源碼
    static boolean isActiveState(State state) {
        return state.isAtLeast(STARTED);
    }
    
    關(guān)鍵點(diǎn)就在State,看下它的源碼
    public enum State {
        /**
         * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
         * any more events. For instance, for an {@link android.app.Activity}, this state is reached
         * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
         */
        DESTROYED,
    
        /**
         * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
         * the state when it is constructed but has not received
         * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
         */
        INITIALIZED,
    
        /**
         * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached in two cases:
         * <ul>
         *     <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
         *     <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
         * </ul>
         */
        CREATED,
    
        /**
         * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached in two cases:
         * <ul>
         *     <li>after {@link android.app.Activity#onStart() onStart} call;
         *     <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
         * </ul>
         */
        STARTED,
    
        /**
         * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached after {@link android.app.Activity#onResume() onResume} is called.
         */
        RESUMED;
    
        /**
         * Compares if this State is greater or equal to the given {@code state}.
         *
         * @param state State to compare with
         * @return true if this State is greater or equal to the given {@code state}
         */
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
    
    對(duì)于isAtLeast()方法調(diào)用了枚舉的compareTo,參數(shù)傳入進(jìn)來的是STARTED,大于等于就剩STARTED,RESUMED,所以我們說LiveData活動(dòng)狀態(tài)只有STARTED,RESUMED。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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