LifeCycle源码杂谈

时间:2021-7-21 作者:qvyue

1.Lifecycle的作用和背景?

我们知道,Activity和Fragment是有其生命周期的。当Activity和Fragment销毁后,我们继续引用将会报错。而且当生命周期内使用时机不当时,也会出现问题。以前我们对Activity和Fragment生命周期的监听可以通过接口,但是这种方式侵入性太强且状态更新也是一大麻烦,没有统一的标准。所以Lifecycle是来解决这个问题的。
我在这里姑且对Lifecycl下个定义:Lifecycle用来解决对组件生命周期及其同步监听问题。

2.Lifecycle成员介绍

要解决这个问题,我们先思考下,如果是你,你会怎么解决?我们知道,设计模式有个模式叫做观察者模式,将被观察者和观察者绑定之后,观察者能监听到被观察者一切活动,所以我们可以设计成观察者模式。那么我们可以这样设计:
Lifecycle:被观察者抽象类
LifecycleObserve:观察者
LifecycleRegistry:Lifecycle具体实现类
LifecycleOwner:被观察者的持有者接口,继承它表明该组件感知生命周期,同时支持外部其他组件监听其生命周期

3.Lifecycle的具体实现

从源码可知,其在Activity中做了几件事情:
1.实现了LifecycleOwner接口,并且返回LifecycleRegistry对象。
2.在onCreate()方法中添加一个ReportFragment。利用Fragment可以同步Activity状态的特性,使用ReportFragment来实现状态的同步。

public class ReportFragment extends Fragment {
     
    ......

    @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) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }
}

可以看到,ReportFragment内部原理也比较简单,主要在各个生命周期阶段调用dispatch()方法。继续追踪下去,发现最后调用LifecycleRegistry.handleLifecycleEvent()方法发送状态事件。

我们看下LifecycleRegistry的源码:

public class LifecycleRegistry extends Lifecycle {

     ......

    private FastSafeIterableMap mObserverMap =
            new FastSafeIterableMap();
    /**
     * Current state
     */
    private State mState;

    /**
     * Sets the current state and notifies the observers.
     * 

* Note that if the {@code currentState} is the same state as the last call to this method, * calling this method has no effect. * * @param event The event that was received */ 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; } 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; } @Override public void addObserver(@NonNull LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver); if (previous != null) { return; } LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { // it is null we should be destroyed. Fallback quickly return; } boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent; State targetState = calculateTargetState(observer); mAddingObserverCounter++; while ((statefulObserver.mState.compareTo(targetState) > ascendingIterator = mObserverMap.iteratorWithAdditions(); while (ascendingIterator.hasNext() && !mNewEventOccurred) { Entry entry = ascendingIterator.next(); ObserverWithState observer = entry.getValue(); while ((observer.mState.compareTo(mState) > descendingIterator = mObserverMap.descendingIterator(); while (descendingIterator.hasNext() && !mNewEventOccurred) { Entry 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)); observer.dispatchEvent(lifecycleOwner, event); popParentState(); } } } // happens only on the top of stack (never in reentrance), // so it doesn't have to take in account parents private void sync() { LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already" + "garbage collected. It is too late to change lifecycle state."); } while (!isSynced()) { mNewEventOccurred = false; // no need to check eldest for nullability, because isSynced does it for us. if (mState.compareTo(mObserverMap.eldest().getValue().mState) newest = mObserverMap.newest(); if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) { forwardPass(lifecycleOwner); } } mNewEventOccurred = false; } static class ObserverWithState { State mState; LifecycleEventObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; } }} ··· 我们看下源码的handleLifecycleEvent()方法,跟踪到sysn()方法,我们详细看下。 isSynced(),这个方法主要判断是否更新状态。主要是比较当前状态mState和mObserverMap中eldestObserverState和newestObserverState的大小比较。 这里有张图,可以看下:![IMG_20210628_125800.jpg](https://upload-images.jianshu.io/upload_images/7632909-f10f6cda72ea5098.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) mObserverMap,即FastSafeIterableMap结构。主要保存LifecycleObserver和它的State,并按从大到小的顺序排列。 比较mState和mObserverMap的状态,直接比较 如果mState比mObserverMap最小的状态还要小,那么调用backwardPass()方法,状态降级。如果mState比mObserverMap最大的状态要大,那么则调用forwardPass()方法,状态升级。(这里发现没有中间状态的判断,我猜想是因为根本就不会有中间态。因为States是升降过程,而mObserverMap会把状态从大到校排列,也就是说如果组件更新了状态,那么它一定是从大的状态降级或者从最小的状态升级,而不会有中间态这种说法)。 继续看下backwardPass()和forwardPass(),其机制差不多,都是遍历元素升级降级的过程,主要看下核心函数:

observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
observer.dispatchEvent(lifecycleOwner, downEvent(observer.mState));

在看下upEvent()和downEvent()的方法:

private static Event downEvent(State state) {
switch (state) {
case INITIALIZED:
throw new IllegalArgumentException();
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
case DESTROYED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException(“Unexpected state value ” + state);
}

private static Event upEvent(State state) {
    switch (state) {
        case INITIALIZED:
        case DESTROYED:
            return ON_CREATE;
        case CREATED:
            return ON_START;
        case STARTED:
            return ON_RESUME;
        case RESUMED:
            throw new IllegalArgumentException();
    }
    throw new IllegalArgumentException("Unexpected state value " + state);
}
这里最好对照图看下,我再贴出来下:
:![IMG_20210628_125800.jpg](https://upload-images.jianshu.io/upload_images/7632909-f10f6cda72ea5098.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
然后我们看下ObserverWithState.dispatchEvent()方法:

static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
        mState = initialState;
    }

    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}
可以看到,最终调用mLifecycleObserver.onStateChanged来更新状态。而mLifecycleObserver 是Lifecycling生成的,我们看下Lifecycling内部:

@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}

    if (isLifecycleEventObserver) {
        return (LifecycleEventObserver) object;
    }

    final Class> klass = object.getClass();
    int type = getObserverConstructorType(klass);
    if (type == GENERATED_CALLBACK) {
        List> constructors =
                sClassToAdapters.get(klass);
        if (constructors.size() == 1) {
            GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                    constructors.get(0), object);
            return new SingleGeneratedAdapterObserver(generatedAdapter);
        }
        GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
        for (int i = 0; i 
从这里可以看出主要有四种LifecycleEventObserver:
FullLifecycleObserver:通过接口更新状态,可以继承DefaultLifecycleObserver来实现监听;
LifecycleEventObserver: 通过注解标记状态,主要通过OnLifecycleEvent接口更新;
SingleGeneratedAdapterObserver
CompositeGeneratedAdaptersObserver:也是通过注解标记状态,但是这个需要继承GeneratedAdapter 手动处理;
ReflectiveGenericLifecycleObserver:通过反射调用更新状态;
回到前面,我们需要看下addObserver()方法:

@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

    if (previous != null) {
        return;
    }
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        // it is null we should be destroyed. Fallback quickly
        return;
    }

    boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
    State targetState = calculateTargetState(observer);
    mAddingObserverCounter++;
    while ((statefulObserver.mState.compareTo(targetState) 
可以看到,主要是将LifecycleObserver添加mObserverMap中并更新状态。
自此,Lifecycle的基本概念全部完毕了。



声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:qvyue@qq.com 进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。