原来你是这样的AAC——Lifecycle的使用及原理

941 阅读10分钟

为什么要用Lifecyle

Android开发中,我们经常需要在功能组件中感知到对应宿主(Activity,Fragment)的生命周期的变化,例如当Activity可见时,在presenter对象中刷新数据,销毁时释放某些资源等等

Lifecycle出来之前,我们一般都用最粗暴的方式,在Activity中手动把在每个生命周期回调分发到功能组件(例如逻辑层presenter)中

但是这种方式存在一些问题,首先代码会显得很臃肿不优雅,每个地方都需要手动处理,多人维护难免出现遗漏

另外还存在一个逻辑上的隐患,假设在onCreate中去开启使用某个资源,对应在onStop中我们需要去释放这个资源,但是onCreate中的操作是个耗时操作,就会存在onStop已经回调完成后,onCreate中的方法却又去开启了这个资源,这种情况这个资源就得不到释放了,会引起内存泄漏

基于这些问题,google为我们提供了Lifecyle,能够简化功能组件感知生命周期的过程,通过观察者模式,自动分发对应生命周期事件

Lifecycle的使用

添加依赖


// 非Androidx 项目
implementation "android.arch.lifecycle:extensions:1.1.1" 

// Androidx 项目
implementation 'androidx.appcompat:appcompat:1.4.1'

如果项目还没迁移到AndroidX,建议尽早迁移

使用

分两大步骤

  1. 把功能组件包装为生命周期观察者
  2. 把观察者与生命周期组件绑定

定义观察者

利用Lifecycle提供的两个接口DefaultLifecycleObserverLifecycleEventObserver,让功能组件具有感知生命周期的能力

DefaultLifecycleObserver提供了onCreate~OnDestroy各个生命周期的回调方法,并提供了默认实现,按需重写

LifecycleEventObserver只提供了一个onStateChanged接口,可根据传入的参数判断当前所处的生命周期状态

旧版本的Lifecycle使用的是LifecycleObserver接口,然后在功能组件中通过注解的方式去添加各个生命周期的回调逻辑,这种使用起来很麻烦,目前已经声明为废弃了

class MyLifecycleObserver : DefaultLifecycleObserver {

    override fun onCreate(owner: LifecycleOwner) {
        Log.i(TAG, "onCreate")
    }

    override fun onResume(owner: LifecycleOwner) {
        Log.i(TAG, "onResume")
    }

    override fun onPause(owner: LifecycleOwner) {
        Log.i(TAG, "onPause")
    }

    override fun onDestroy(owner: LifecycleOwner) {
        Log.i(TAG, "onDestroy")
    }

    companion object {
        const val TAG = "MyLifecycleObserver"
    }

}

这样这个MyLifecycleObserver就具备了感知生命周期的能力,当他跟对应生命周期宿主绑定之后,就能在对应接口中收到回调

观察者和生命周期绑定

绑定的过程可理解为给生命周期宿主(Activity等)添加观察者的过程,利用LifecycleOwner接口的getLifecycle函数,获取到当前宿主的Lifecycle对象,通过这个Lifecycle对象的addObserver方法,就能把生命周期组件和功能组件关联起来,建立观察关系,AppCompatActivity已实现了LifecycleOwner(父类ComponentActivity实现的)

class LifecycleActivity : AppCompatActivity() {

    private val mBinding by lazy {
        ActivityLifecycleBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle/?) {
        super.onCreate(savedInstanceState)
        Log.i(TAG, "activity onCreate")
        setContentView(mBinding.root)
        lifecycle.addObserver(MyLifecycleObserver())
    }

    override fun onResume() {
        super.onResume()
        Log.i(TAG, "activity onResume")
    }

    override fun onPause() {
        super.onPause()
        Log.i(TAG, "activity onResume")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(TAG, "activity onDestroy")

    }

    companion object {
        const val TAG = "LifecycleActivity"
    }

}

运行结果

I/LifecycleActivity: activity onCreate
I/MyLifecycleObserver: onCreate
I/LifecycleActivity: activity onResume
I/MyLifecycleObserver: onResume
I/MyLifecycleObserver: onPause
I/LifecycleActivity: activity onPause
I/MyLifecycleObserver: onDestroy
I/LifecycleActivity: activity onDestroy

可以看到MyLifecycleObserver和Activity的生命周期回调保持了同步,不过细心的童鞋可能已经注意到这里有一个点很有意思,在OnResume之前,都是Activity中的日志先打印,然后才打印Observer中的日志,而在OnResume之后,却是observer中的先执行,这是为啥勒?看图(这个图很关键

image.png

图中states是Lifecycle为生命周期定义的5中状态INITIALIZED,DESTROYED,CREATED,STARTED,RESUMED

以RESUMED状态为例,ON_RESUME即代表onResume方法的回调执行,这个方法执行完成之后,Activity才进入到了RESUMED状态,而对于ON_PAUSE,也就是onPause刚开始执行的时候还是在Resumed态,执行后就进入了STARTED状态。

所以对应就是onResumed执行之后,lifecycle才会分发对应的ON_RESUME事件到observer中,而onPause刚开始执行,就会把ON_PAUSE事件分发到observer中,这样做的好处是当observer收到对应的事件时,对应Activity所处的生命周期状态是准确的

Lifecyle原理

从两个角度进行分析

  1. 观察者跟生命周期组件如何建立绑定
  2. 生命周期事件如何回调到观察者

注册观察者

观察者跟生命周期组件如何建立绑定,也就是看看addObserver的背后都干了什么,上面的例子中,我们在addObserver的时候,是先调用了getLifecycle函数,跟一下这个函数,发现是一个接口LifecycleOwner提供的,而Activity实现了这个接口

LifecyclerOwner

一个非常简单的接口,只提供了一个函数,getLifecycle,返回一个Lifecycle对象,而Lifecycle类是Lifecycle库的核心,用于把生命周期分发出去,这里接口和类的名字就很好理解,LifecycleOwner表示生命周期所有者

public interface LifecycleOwner {
    /**
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

所以具备生命周期的类都可以去实现这个接口,在AndroidX内已有三个类实现了LifecycleOwner接口,分别是Activity,Fragment,以及ProcessLifecycleOwnerProcessLifecycleOwner用于监听应用的生命周期,包括前后台切换,不过需要额外引入依赖

implementation "androidx.lifecycle:lifecycle-process:$lifecycle"

Lifecycle Lifecycle是一个抽象类,定义了一个具有生命周期的对象

image.png

这个类主要定义了两个枚举类,EventState

public enum Event {
   
    ON_CREATE,
   
    ON_START,
   
    ON_RESUME,
   
    ON_PAUSE,
   
    ON_STOP,
    
    ON_DESTROY,
   
    ON_ANY;
}
public enum State {
    
    DESTROYED,

    INITIALIZED,

    CREATED,

    STARTED,

    RESUMED;
}

Event表示会分发给其他组件的生命周期事件,ON_ANY表示任意事件都会触发

State表示当前生命周期所有者所处的状态,跟上面提到的那张图是对应上的

不知道大家会不会有疑问,为什么要搞出这两个值,直接分发具体的event事件不就够了?不香么?这里留个疑问,后面会讲到

另外还有两个抽象方法addObserver和removeObserver

// 添加观察者
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);

// 移除观察者
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);

LifecycleRegistry Lifecycle的实现类,负责添加观察者,分发生命周期事件给观察者,看看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;
    }
    // 省略部分代码
}

这里省略了一些逻辑,看重点,很显然把observer放到了一个mObserverMap当中,实际上这个不是真正意义上的Map,而是一个自定义的可在遍历过程中增删observer的数据结构,此处先不深凿了,注意这里把添加进来的Observer对象包装到了一个ObserverWithState对象中,注意这个对象,后面会用到

事件如何分发

那么到底是怎么感知到Activity等组件的生命周期的变化,并分发给所有observer的了?

直接看看ComponentActivity的源码

private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

public Lifecycle getLifecycle() {
    return mLifecycleRegistry;
}

getLifecycle返回了一个LifecycleRegistry对象,再看看onCreate回调

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSavedStateRegistryController.performRestore(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
    if (mContentLayoutId != 0) {
        setContentView(mContentLayoutId);
    }
}

然而并没有看到LifecycleRegistry对象,不过这个ReportFragment是lifecycle库下的类,那跟他肯定有点儿关系了,点进去看看

public class ReportFragment extends android.app.Fragment {

    public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            LifecycleCallbacks.registerIn(activity);
        }
        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();
        }
    }
    

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatchCreate(mProcessListener);
        dispatch(Lifecycle.Event.ON_CREATE);
    }
    
    static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
        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);
            }
        }
    }
}

果然,这不就跟glide感知生命周期的做法一样,用了一个没有界面的Fragment,通过fragment感知宿主Activity的生命周期变化,然后分发出去

感知到生命周期的变化之后,会把对应生命周期事件的event通过LifecycleRegistry的handleLifecycleEvent分发出去,再跟下这块儿代码

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    enforceMainThreadIfNeeded("handleLifecycleEvent");
    moveToState(event.getTargetState());
}

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 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) < 0) {
            backwardPass(lifecycleOwner);
        }
        Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            forwardPass(lifecycleOwner);
        }
    }
    mNewEventOccurred = false;
}

通过Event的getTargetState()获取到到当前的生命周期状态State值,然后就准备向observer分发当前的生命周期状态,这里会把当前所拿到的最新State状态和Observer目前的State状态进行比较,如果最新状态比Observer的状态要小,这里小需要看枚举的比较,定义在前面的比定义在后面的小,这里要对照state状态和那张图一起看就很好理解

    public enum State {

        DESTROYED,

        INITIALIZED,

        CREATED,

        STARTED,

        RESUMED;
    }

假设旧的状态是RESUMED,而最新的是STARTED,这时就表示新的状态比旧的状态要小,就会走到backwardPass函数里面,反之则会走到forwardPass


private void backwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
            mObserverMap.descendingIterator();
    while (descendingIterator.hasNext() && !mNewEventOccurred) {
        Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
        ObserverWithState observer = entry.getValue();
        while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            Event event = Event.downFrom(observer.mState);
            if (event == null) {
                throw new IllegalStateException("no event down from " + observer.mState);
            }
            pushParentState(event.getTargetState());
            observer.dispatchEvent(lifecycleOwner, event);
            popParentState();
        }
    }
}

直接看看backwardPass,这里对mObserverMap进行了遍历,把当前遍历到的observer对应state取出来,通过Event.downFrom计算出需要分发的事件,最后通过dispatchEvent分发出去

所以前面抛出的那个问题,为什么需要state和event,这里看到他的妙处了吧,因为不是每一个observer都是处于同一状态的,因为有可能observer的状态还没更新完,新的事件又来了,这样就会重新遍历,所以会出现有的observer的状态更最新的状态之间不是连续的,这样通过最新的State值和当前的State值,就可以把这之间的所有生命周期事件都回调一遍,否则有的生命周期事件就可能错过了,那写在里面的逻辑永远得不到执行,当然addObserver的时候,也是利用这个,让刚新注册的observer,能把注册之前走过的所有生命周期事件都走一遍,所以这是一种粘性事件

再看看addObserver的这部分代码,通过while循环,把之前的所有事件都分发了一遍

public void addObserver(@NonNull LifecycleObserver 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--;
}

再来看看dispatchEvent

void dispatchEvent(LifecycleOwner owner, Event event) {
    State newState = event.getTargetState();
    mState = min(mState, newState);
    mLifecycleObserver.onStateChanged(owner, event);
    mState = newState;
}

很简单,调用了LifecycleEventObserver的onStateChanged方法分发了出去,不过我们前面说过,我们一般还会使用实现DefaultLifecycleObserver的方式,这种是怎么回调到的?

我们可以看到DefaultLifecycleObserver是继承FullLifecycleObserver的,而LifecycleEventObserver有一个实现类FullLifecycleObserverAdapter

@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
    switch (event) {
        case ON_CREATE:
            mFullLifecycleObserver.onCreate(source);
            break;
        case ON_START:
            mFullLifecycleObserver.onStart(source);
            break;
        case ON_RESUME:
            mFullLifecycleObserver.onResume(source);
            break;
        case ON_PAUSE:
            mFullLifecycleObserver.onPause(source);
            break;
        case ON_STOP:
            mFullLifecycleObserver.onStop(source);
            break;
        case ON_DESTROY:
            mFullLifecycleObserver.onDestroy(source);
            break;
        case ON_ANY:
            throw new IllegalArgumentException("ON_ANY must not been send by anybody");
    }
    if (mLifecycleEventObserver != null) {
        mLifecycleEventObserver.onStateChanged(source, event);
    }
}

看到这很容易猜想到,DefaultLifecycleObserver的实现类,会被包装到这里面,然后分发

还记得之前提到的,在addObserver的时候,会把添加进来的observer对象包装到ObserverWithState中么,看看这个类的构造函数

ObserverWithState(LifecycleObserver observer, State initialState) {
    mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
    mState = initialState;
}
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);
    }
    // 省略部分代码
}

果然 ,在这里,通过Lifecycling,把add进来的observer包装到了FullLifecycleObserverAdapter中,并把FullLifecycleObserverAdapter对象返回赋值给了ObserverWithState对象的mLifecycleObserver属性,所以最后dispatchEvent中调用的的mLifecycleObserver.onStateChanged(owner, event)就通过Adapter回调给了对应的observer的函数

到这里,从绑定observer到回调生命周期的流程就走通了