LiveData源码分析

前言

公司的项目使用的是MVVM设计模式,自然离不开LiveData,今天就来学习一波LiveData相关的源码。

如何感知生命周期

LiveData是在LifeCycle包下的,使用LiveData首先来了解一下LifeCycle是如何感知生命周期的。

下图Activity的继承体系:
LiveData源码分析_第1张图片

其中有一个SupportActivity

public class SupportActivity extends Activity implements LifecycleOwner {
    ……
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    ……
    @Override
    @SuppressWarnings("RestrictedApi")
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }

    @CallSuper
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
        super.onSaveInstanceState(outState);
    }
    ……

其中ReportFragment.injectIfNeededIn(this);一句很关键,这里注入了一个ReportFragment到当前Activity中:

    public static void injectIfNeededIn(Activity activity) {
        // ProcessLifecycleOwner should always correctly work and some activities may not extend
        // FragmentActivity from support lib, so we use framework fragments for activities
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            // 如果没有注入过,注入
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // Hopefully, we are the first to make a transaction.
            manager.executePendingTransactions();
        }
    }

那ReportFragment是干嘛的呢?来看一下它的主要方法:

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatchCreate(mProcessListener);
        dispatch(Lifecycle.Event.ON_CREATE);
    }

    @Override
    public void onStart() {
        super.onStart();
        dispatchStart(mProcessListener);
        dispatch(Lifecycle.Event.ON_START);
    }

    @Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        dispatch(Lifecycle.Event.ON_RESUME);
    }

    @Override
    public void onPause() {
        super.onPause();
        dispatch(Lifecycle.Event.ON_PAUSE);
    }

    @Override
    public void onStop() {
        super.onStop();
        dispatch(Lifecycle.Event.ON_STOP);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispatch(Lifecycle.Event.ON_DESTROY);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }

    private void dispatch(Lifecycle.Event event) {
        // 分发生命周期的事件
        Activity activity = getActivity();
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }

        if (activity instanceof LifecycleOwner) {
            // 如果继承自SupportActivity,getLifecycle()得到的就是SupportActivity的成员变量一个LifecycleRegistry
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                // 让LifecycleRegistry去处理生命周期事件
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }

我们看到在ReportFragment的生命周期里去分发了对应生命周期的事件,而ReportFragment又是和Activity绑定的,那么分发的其实就是Activity对应的生命周期事件。

以上代码涉及到了LifecycleRegistry,回到SupportActivity,我们可以看到private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }

顾名思义就是LifeCycle的登记处,它以弱引用的方式持有了当前的Activity。当Activity生命周期改变的时候,它会去处理对应的生命周期事件。

那如果是在Fragment中注册观察者呢?来看下v4包下的Fragment:

    LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
    ……

    void performCreate(Bundle savedInstanceState) {
        if (mChildFragmentManager != null) {
            mChildFragmentManager.noteStateNotSaved();
        }
        mState = CREATED;
        mCalled = false;
        onCreate(savedInstanceState);
        mIsCreated = true;
        if (!mCalled) {
            throw new SuperNotCalledException("Fragment " + this
                    + " did not call through to super.onCreate()");
        }
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }
    ……

    void performStart() {
        if (mChildFragmentManager != null) {
            mChildFragmentManager.noteStateNotSaved();
            mChildFragmentManager.execPendingActions();
        }
        mState = STARTED;
        mCalled = false;
        onStart();
        if (!mCalled) {
            throw new SuperNotCalledException("Fragment " + this
                    + " did not call through to super.onStart()");
        }
        if (mChildFragmentManager != null) {
            mChildFragmentManager.dispatchStart();
        }
        if (mLoaderManager != null) {
            mLoaderManager.doReportStart();
        }
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }

查看源码,会发现和Activity类似,也有一个成员变量LifecycleRegistry来持有Fragment。并且在Fragment生命周期变化之后,会将生命周期事件分发出去。

接着进入LifecycleRegistry的handleLifecycleEvent()

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        // 根据生命周期事件得到对应的状态
        State next = getStateAfter(event);
        // 调整到对应的状态
        moveToState(next);
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        // 同步状态给各个观察者
        sync();
        mHandlingEvent = false;
    }

继续进入sync():

    private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
                    + "new events from it.");
            return;
        }
        while (!isSynced()) {
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                // 倒序遍历,通知观察者,去修改状态
                backwardPass(lifecycleOwner);
            }
            Entry newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                // 正序遍历,通知观察者,去修改状态 
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

LiveData注册观察者

一般我们这样使用:

        liveData.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {

            }
        }); 
  

这里的this就是Activity或者Fragment,我们进入observe():

    @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {
        // 判断当前LifeCycle的状态
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            // 如果处于销毁状态,直接返回
            return;
        }
        // 将LifecycleOwner和Observer包装了一层
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        // 判断Observer有没有被添加过,如果没有则添加到一个HashMap中
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        if (existing != null && !existing.isAttachedTo(owner)) {
            // 如果添加过,抛出异常
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        // 将包装过的Observer添加到LifecycleRegistry
        owner.getLifecycle().addObserver(wrapper);
    }

继续进入LifecycleRegistry的addObserver():

    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        // 将LifecycleObserver包装为ObserverWithState
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        // 如果没有保存过就存入mObserverMap
        // mObserverMap是一个可以在迭代过程中修改的HashMap
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        ……

LiveData数据设置

LiveData有两种方式设置数据,第一种setValue(),在主线程中使用:

    @MainThread
    protected void setValue(T value) {
        assertMainThread("setValue");
        mVersion++;
        mData = value;
        dispatchingValue(null);
    }

另一种postValue(),可以在子线程中使用:

    protected void postValue(T value) {
        boolean postTask;
        synchronized (mDataLock) {
            postTask = mPendingData == NOT_SET;
            mPendingData = value;
        }
        if (!postTask) {
            return;
        }
        ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
    }

    private final Runnable mPostValueRunnable = new Runnable() {
        @Override
        public void run() {
            Object newValue;
            synchronized (mDataLock) {
                newValue = mPendingData;
                mPendingData = NOT_SET;
            }
            //noinspection unchecked
            setValue((T) newValue);
        }
    };

其中AppToolkitTaskExecutor通过一个以MainLooper作为Looper的Handler将mPostValueRunnable发送到主线程上,最终还是调用了setValue()

setValue()中调用了dispatchingValue(),进而调用了considerNotify()来通知数据的改变:

    private void considerNotify(ObserverWrapper observer) {
        if (!observer.mActive) {
            // 如果观察不处于激活状态
            return;
        }
        // Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.
        //
        // we still first check observer.active to keep it as the entrance for events. So even if
        // the observer moved to an active state, if we've not received that event, we better not
        // notify for a more predictable notification order.
        if (!observer.shouldBeActive()) {
            // 如果不应该被激活
            observer.activeStateChanged(false);
            return;
        }
        if (observer.mLastVersion >= mVersion) {
            // 如果不是最新版本
            return;
        }
        observer.mLastVersion = mVersion;
        //noinspection unchecked
        // 最终调用观察者的onChanged()回调
        observer.mObserver.onChanged((T) mData);
    }

观察者的移除

上文说到过Observer会被包装成LifecycleBoundObserver,LifecycleBoundObserver的onStateChanged()在状态改变时会被调用:

        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                // 如果是销毁状态,会将该观察者从观察者列表中移除
                // 避免了内存泄露
                removeObserver(mObserver);
                return;
            }
            activeStateChanged(shouldBeActive());
        }

参考:

  1. LiveData 源码分析

  2. Android Architecture Components 源码分析

你可能感兴趣的:(Android)