Google Architecture之LiveData、Vie

2019-01-01  本文已影响13人  Senble

一、我们想象中的生命周期感应应该是怎样的?

1、设想

监听过程如果让我们开始自己去实现一个简单的生命周期感应框架,刚开始很可能是这样的。


first_glance.png

自己实现一个Data<T>,里面有一个集合,保存所有的Observer。同时BaseActivity包含一个Data的集合,当生命周期变化的时候去动态注销UI和Data的订阅关系。

2、google的实现

google_implement.png
google把生命周期处理逻辑抽离到一个单独的LifecycleRegistry中,并将数据的逻辑放在LiveData中,职责更加清晰明了。
在多线程处理,LiveData状态的保持,以及事件的变化传递控制更加细致具体。

二、Observer监听过程以及生命周期感应

1、监听过程

(1·1)LiveData.observe()

    //LiveData::observe()
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        //(装饰者模式)封装成一个能一个能接收并处理生命周期事件的LifecycleBoundObserver类,
        //LifecycleBoundObserver会当FragmentActivity/Fragment的onDestroy()调用之后将所有的监听关系移除掉
        //LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        //将observer作为key添加到Map中(注意:同一个liveData能被多个observer监听)
        //注意防止重复监听导致逻辑可能出错,例如重复执行网络请求的时候很容易多次发生多次监听
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        //同一个Observer对象不能绑定多个不同拥有生命周期的对象
        if (existing != null && !existing.isAttachedTo(owner)) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        //参见2
        owner.getLifecycle().addObserver(wrapper);
    }

LifecycleBoundObserver类

class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
        @NonNull final LifecycleOwner mOwner;

        LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<T> observer) {
            super(observer);
            mOwner = owner;
        }

        @Override
        boolean shouldBeActive() {
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }

        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            activeStateChanged(shouldBeActive());
        }

        @Override
        boolean isAttachedTo(LifecycleOwner owner) {
            return mOwner == owner;
        }

        @Override
        void detachObserver() {
            mOwner.getLifecycle().removeObserver(this);
        }
    }

(1·2)owner.getLifecycle().addObserver(wrapper);

    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        //将Observer添加到mObserverMap中,此处被封装成一个ObserverWithState类(具有状态属性)
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        
        if (previous != null) {
            return;
        }
        //省略observer与LifecycleRegistry状态同步逻辑(后面有分析).....
    }

ObserverWithState类

    //
    //ObserverWithState::dispatchEvent()
    //接收生命周期事件,并进行状态的变更,同时将事件传递给GenericLifecycleObserver处理
    //(其实也就是上面第一步的LifecycleBoundObserver),方便进行监听关系的注销
    void dispatchEvent(LifecycleOwner owner, Event event) {
            //计算接收Event事件之后应该处于哪种状态
            State newState = getStateAfter(event);
            mState = min(mState, newState);//此句多余
            mLifecycleObserver.onStateChanged(owner, event);
            //更新并记录新状态
            mState = newState;
        }

2、生命周期的感应

(2·1)生命周期的捕获

记得在步骤(1·1)中需要传入一个实现了LifecycleOwner接口的对象。而我们一般传入的是FragmentActivity/Fragment,此时我们直接点开FragmentActivity源码之后一层层剥掉其外壳,将会发现它的父类SupportActivity其实实现了LifecycleOwner接口,并且会通过接口的getLifecycle()方法返回一个Lifecycle的子类(也就是LifecycleRegstry)。

SupportActivity这个类代码并不多,大致看一下就能明白其意思

重点: 你会发现这行代码

protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在FragmentActivity上面添加一个无界面的Fragment(利用Fragment生命周期和Activity/Fragment绑定在一起的特点,
        //实现hook到Activity/Fragment的生命周期事件,将其整合到一起处理,达到低耦合高内聚的目的)。有兴趣的可以去分
        //析glide的动态取消加载图片请求逻辑,甚至可以自己开发一个动态取消网络请求的网络库开源项目。
        ReportFragment.injectIfNeededIn(this);
    }

在ReportFragment的各个生命周期回调方法中会调用dispatch(Lifecycle.Event event)方法,将生命周期事件传递给前面提到过的Lifecycle的子类(也就是LifecycleRegstry)。

private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        //LifecycleRegistryOwner目前已标记弃用,可不管
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }
        
        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                //将事件传递给LifecycleRegstry对象
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }

分析到这里我们大致总结一下:(同时可以加入一些猜想和自己的理解)

现在FragmentActivity/Fragment的生命周期事件会通过ReportFragment传递给LifecycleRegistry。
然后我们大胆猜想下,在LifecycleRegistry在处理事件的时候是否当收到on_destroy事件的时候就通过前面步骤(1·2)中的ObserverWithState类通知Observer,然后进行Observer的监听注销呢?

带着疑问和猜想,我们继续去分析LifecycleRegistry中的逻辑。

(2·2)LifecycleRegistry生命周期事件的处理以及状态变化

在讲这部分逻辑之前,需要将里面涉及到的几个重要的状态变化方法逻辑图理一遍。

其实这部分状态机的变化图你也可以不用花这么大精力去理解,因为我们真正关心的只有on_destroy事件,只有收到它我们才会去注销监听关系。所以本部分逻辑你可以不需要深入理解。

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;
        }
        //根据当前的状态mState,去更新Map中Observer的状态
        //mHandlingEvent在addObserver(@NonNull LifecycleObserver observer)方法会用到
        //用来判断协同是否有正在进行相同的sync逻辑,避免重复执行
        mHandlingEvent = true;
        //根据当前的状态mState,去更新Map中Observer的状态
        sync();
        mHandlingEvent = false;
    }

moveToState() -----> sync()

//同步所有的Observer与LifecycleResitry的状态(也就是Activity/Fragment的状态)
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;
        }
        //isSynced()会判断当前map中头尾的Observer状态与LifecycleRegistry中mState一致
        //不一致表示在sync同步状态过程中有新的Observer加入map中了
        while (!isSynced()) {
            mNewEventOccurred = false;
            //Activity/Fragment状态从被销毁或启动其它界面时,与其绑定的Observer状态的同步
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            //Activity/Fragment启动时,与其绑定的Observer状态的同步
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

moveToState() -----> backwardPass()
或者
moveToState() -----> forwardPass()

    //Activity/Fragment启动时,与其绑定的Observer状态的同步
    //注意: 多个Observer监听同一个LiveData,并且Observer 中有相同的逻辑处理,
    //最终的处理结果以最后添加的Observer中的逻辑为准。
    private void forwardPass(LifecycleOwner lifecycleOwner) {
        //mObserverMap从Start到End进行遍历(最早添加-->最近添加,越早越靠前)。
        //这里的ascendingIterator就是上面现象的原因,具体翻阅源码分析下
        Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                //while state in observer.mState到mState,逐次计算出触发状态变化的事件,传递给
                //ObserverWithState处理
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }
    //Activity/Fragment状态从被销毁或启动其它界面时,与其绑定的Observer状态的同步
    private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                //将生命周期shijian传递给ObserverWithState
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }

ObserverWithState

ObserverWithState是LifecycleRegistry的内部类

static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        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);
            //改变ObserverWithState状态,同时将生命周期Event传递给LifecycleBoundObserver
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

LifecycleBoundObserver

LifecycleBoundObserver是LiveData的内部类

class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
        @NonNull final LifecycleOwner mOwner;

        LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<T> observer) {
            super(observer);
            mOwner = owner;
        }

        //状态为Started或Resumed才处于激活状态
        @Override
        boolean shouldBeActive() {
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }

        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            //注意:如果Observer绑定的Activity/Fragment处于DESTROYED(onDestroy方法调用之后)状态,就将所有的观察订阅关系注销
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            activeStateChanged(shouldBeActive());
        }

        @Override
        boolean isAttachedTo(LifecycleOwner owner) {
            return mOwner == owner;
        }

        @Override
        void detachObserver() {
            mOwner.getLifecycle().removeObserver(this);
        }
    }

LiveData:

    @MainThread
    public void removeObserver(@NonNull final Observer<T> observer) {
        assertMainThread("removeObserver");
        //移除LiveData中的Observer
        ObserverWrapper removed = mObservers.remove(observer);
        if (removed == null) {
            return;
        }
        //调用LifecycleBoundObserver的detachObserver()方法
        //也就是移除LifecycleRegistry中的Observer引用
        removed.detachObserver();
        //更改observer的状态
        removed.activeStateChanged(false);
    }

(2·3)关键方法状态变化逻辑图

回顾下Activity的生命周期:

activity_lifecycle.png

LifecycleRegistry的状态转换图:

google_lifecycle.png

LifecycleRegistry的状态转换关键控制方法:

key_function.png

3、Observer状态与Registry的同步

LifecycleRegistry的方法sync()只在两个地方调用到了:

  1. LifecycleRegistry::addObserver(@NonNull LifecycleObserver observer)
  2. LifecycleRegistry::moveToState(State next)
@Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        
        ......
        
        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            pushParentState(statefulObserver.mState);
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }

        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }
private void moveToState(State next) {
        
        ......
        
        //根据当前的状态mState,去更新Map中Observer的状态
        //mHandlingEvent在addObserver(@NonNull LifecycleObserver observer)方法会用到
        //用来判断协同是否有正在进行相同的sync逻辑,避免重复执行
        mHandlingEvent = true;
        //根据当前的状态mState,去更新Map中Observer的状态
        sync();
        mHandlingEvent = false;
    }

因为涉及到多线程操作(如addObserver可能在其他线程执行)。这里的总体逻辑就是如果当前只要有一个地方在执行sync操作,另一个都无须再次执行sync方法进行同步。
这和sync方法的逻辑有关

while(!isSynced()){
    ...
}

isSynced方法就是判断当前LifecycleRegistry状态mState是否和Map中的首位的Observer状态是否一致(因为每次添加新的Observer都会触发sync,所以每次只要判断首尾Observer就行)。

意思就是只要首尾不一致,就肯定不同步。
首尾一致,因为同步是遍历的,那么肯定同步。

private boolean isSynced() {
        if (mObserverMap.size() == 0) {
            return true;
        }
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
        State newestObserverState = mObserverMap.newest().getValue().mState;
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }

4、ViewModel的生命周期管理

这部分相对简单很多。逻辑主要在FragmentActivity的以下三个方法中

  1. onCreate()
  2. onRetainNonConfigurationInstance()
  3. onDestroy()
protected void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    // 恢复mViewModelStore
    FragmentActivity.NonConfigurationInstances nc = (FragmentActivity.NonConfigurationInstances)this.getLastNonConfigurationInstance();
    if (nc != null && nc.viewModelStore != null && this.mViewModelStore == null) {
        this.mViewModelStore = nc.viewModelStore;
    }
        
    ...
}
protected void onDestroy() {
        super.onDestroy();
        //Configurations发生变化而引起的onDestroy不会销毁ViewModel
        if (this.mViewModelStore != null && !this.isChangingConfigurations()) {
            this.mViewModelStore.clear();
        }

        this.mFragments.dispatchDestroy();
    }
//mViewModelStore的持久化
public final Object onRetainNonConfigurationInstance() {
        Object custom = this.onRetainCustomNonConfigurationInstance();
        FragmentManagerNonConfig fragments = this.mFragments.retainNestedNonConfig();
        if (fragments == null && this.mViewModelStore == null && custom == null) {
            return null;
        } else {
            FragmentActivity.NonConfigurationInstances nci = new FragmentActivity.NonConfigurationInstances();
            nci.custom = custom;
            nci.viewModelStore = this.mViewModelStore;
            nci.fragments = fragments;
            return nci;
        }
    }

5、总结

  1. 不同Observe监听相同LiveData,生命周期没控制好,导致崩溃
  2. 多个不同Observer监听同一个LiveData,并且Observer 中有相同的逻辑处理,最终的处理结果以最后添加的Observer中的逻辑为准。
  3. 默认的Observer的只会在Activity或Fragment处于onStarted/onResumed状态下才会接收到LiveData的数据;或者重新处于onStarted/onResumed时。

6、思考

  1. 如何在不同的Activity之间共享ViewModel?
    答:自己去实现一个ViewModelStore,自己控制它的生命周期。
  2. ViewModel是否帮我们做了数据持久化?
    答:ViewModel没做数据的持久化,只是内存变量的复用。
  3. 怎样让observer处于onCreated状态也能处理数据?
    答:目前并没有提供对应API去自定义Observer的逻辑触发时机。
上一篇下一篇

猜你喜欢

热点阅读