JetPack Lifecycle
1 .Lifecyle组件简介
LifeCycle组件是一个用于观察activity/fragment生命周期的组件。
2.相关类
1.Lifecycle 是一个类,用于存储有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态。
图 1. 构成 Android Activity 生命周期的状态和事件
类可以通过实现 DefaultLifecycleObserver 并替换相应的方法(如 onCreate 和 onStart 等)来监控组件的生命周期状态。然后,您可以通过调用 Lifecycle 类的 addObserver() 方法并传递观察器的实例来添加观察器。
2.LiveData是怎么观察生命周期的
如LiveData组件时可以观察到activity/frament 的生命周期,也是这样做的,如下所示:
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
assertMainThread("observe");
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
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;
}
owner.getLifecycle().addObserver(wrapper);
}
上面时LiveData的observer方法,可以看到在方法最后,获取owner的lifecycle,添加了一个observer,这个lifecycleBoundObserver实现了LifecycleEventObserver接口,如下:
class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
@NonNull
final LifecycleOwner mOwner;
LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<? super T> observer) {
super(observer);
mOwner = owner;
}
@Override
boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
Lifecycle.State currentState = mOwner.getLifecycle().getCurrentState();
if (currentState == DESTROYED) {
removeObserver(mObserver);
return;
}
Lifecycle.State prevState = null;
while (prevState != currentState) {
prevState = currentState;
activeStateChanged(shouldBeActive());
currentState = mOwner.getLifecycle().getCurrentState();
}
}
@Override
boolean isAttachedTo(LifecycleOwner owner) {
return mOwner == owner;
}
@Override
void detachObserver() {
mOwner.getLifecycle().removeObserver(this);
}
}
LifecycleEventObserver继承了LifecycleObserver,里面定义了一个方法
public interface LifecycleEventObserver extends LifecycleObserver {
/**
* Called when a state transition event happens.
*
* @param source The source of the event
* @param event The event
*/
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
先总结一下,当lifecycle观察到activity、fragment生命周期改变时,会查找存在其内部的observer,然后会回调observer的onStateChanged方法,让observer可以观测到生命周期变化。
3.lifecycle是怎么观察生命周期的
下面看一下lifecycle是怎么观察activity、fragment的生命周期的。
首先我们activity实现了LifecycleOwner接口
顺着AppCompatActivity往上找–>FragmentActivity–>ComponentActivity
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
ContextAware,
//注意这里
LifecycleOwner,
ViewModelStoreOwner,
HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner,
ActivityResultRegistryOwner,
ActivityResultCaller {
.........
可以看到实现了LifeCycleOwner接口
然后再看FragmentActivity,在该类里面创建了一个LifecycleRegistry,用来监听生命周期变化并分发给注册的observer,如下代码:
final LifecycleRegistry mFragmentLifecycleRegistry = new LifecycleRegistry(this);
当FragmentActivity生命周期变化时:
onCreate
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
mFragments.dispatchCreate();
}
onStart
@Override
protected void onStart() {
super.onStart();
mStopped = false;
if (!mCreated) {
mCreated = true;
mFragments.dispatchActivityCreated();
}
mFragments.noteStateNotSaved();
mFragments.execPendingActions();
// NOTE: HC onStart goes here.
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
mFragments.dispatchStart();
}
onResume
@Override
protected void onPostResume() {
super.onPostResume();
onResumeFragments();
}
/**
* This is the fragment-orientated version of {@link #onResume()} that you
* can override to perform operations in the Activity at the same point
* where its fragments are resumed. Be sure to always call through to
* the super-class.
*/
protected void onResumeFragments() {
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mFragments.dispatchResume();
}
onPause
@Override
protected void onPause() {
super.onPause();
mResumed = false;
mFragments.dispatchPause();
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
onStop
@Override
protected void onStop() {
super.onStop();
mStopped = true;
markFragmentsCreated();
mFragments.dispatchStop();
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
}
onDestory
@Override
protected void onDestroy() {
super.onDestroy();
mFragments.dispatchDestroy();
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
}
可以看到,在生命周期各个函数内部都调用了
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
首先看一下FragmentLifecycleRegistry的构造函数
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
this(provider, true);
}
private LifecycleRegistry(@NonNull LifecycleOwner provider, boolean enforceMainThread) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
mEnforceMainThread = enforceMainThread;
}
很简单就是将传进来实现了LifecycleOwner的FragmentActivity放到一个软引用里面,然后将当前mState赋值为INITIALIZED(初始状态)
然后看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;
}
调用event.getTargetState(),然后调用了moveToState方法,看一下event.getTargetState()方法中做了什么
@NonNull
public State getTargetState() {
switch (this) {
case ON_CREATE:
case ON_STOP:
return State.CREATED;
case ON_START:
case ON_PAUSE:
return State.STARTED;
case ON_RESUME:
return State.RESUMED;
case ON_DESTROY:
return State.DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException(this + " has no target state");
}
可以说将状态又归类了一下,
ON_CREATE||ON_STOP,对应State.CREATED,
ON_START||ON_PAUSE对应State.STARTED,
ON_RESUME对应State.RESUMED,
ON_DESTROY对应State.DESTROYED
然后看moveToState方法,如果下一个传进来state等于上一个state,则返回,如果不等于就将传进来的state赋值给mState,然后执行sync方法
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;
}
这里可以看到,如果lifecycleOwner如果为null,则抛出异常,然后判断当前是否时同步状态,如果不是,则执行其中的代码。
其中可以看到需要从mObserverMap取数据,那么这个mObserverMap是什么
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
可以看到实在LifeCycleRegistry创建的时候创建的,key为LifecycleObserver,value为ObserverWithState,既然要取,肯定要存,看一下addObserver方法做了什么。
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
// 判断当前状态是否是DESTROYED ,如果不是则为INITIALIZED状态
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 创建ObserverWithState ,并将observer和initialState传递进入
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// 然后将observer,statefulObserver存入mObserverMap中
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
...........省略部分代码
}
看一下ObserverWithState 做了什么
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 = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
可以看到调用了Lifecycling.lifecycleEventObserver(observer);然后将传进来initialState保存起来,然后其中写了一个dispatchEvent方法。看一下Lifecycling.lifecycleEventObserver(observer)方法做了什么
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;
}
......省略部分代码
可以看到就是对传进来observer判断是实现了LifecycleEventObserver,还是实现了FullLifecycleObserver。这里我们以实现了LifecycleEventObserver举例,因为LiveData中的observer就是实现了LifecycleEventObserver,好了,现在返回了一个LifecycleEventObserver。
然后再回头看刚才的sync()方法,当中执行了以下代码
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
mObserverMap.eldest()获取最早添加的Entry,这个Entry就是我们在addObserver方法中通过putIfAbsent添加的
public V putIfAbsent(@NonNull K key, @NonNull V v) {
Entry<K, V> entry = get(key);
if (entry != null) {
return entry.mValue;
}
put(key, v);
return null;
}
可以看到Entry也是以我们传进来的key为索引的。所以mObserverMap.eldest().getValue()就是获取我们addObserver方法中添加的ObserverWithState,然后获取其中的mState进行一个compareTo方法。
介绍一下compareTo()方法
Enum类的compareTo()方法比较同一枚举类型的两个枚举常量。它返回两个枚举常量的序数差。如果两个枚举常量相同,则返回零。
当此 Enum 对象等于或与给定的 Enum 对象相同时,它返回 0。
当此 Enum 对象大于给定的 Enum 对象时,它返回正值。
当此 Enum 对象小于给定的 Enum 对象时,它返回负值。
具体实例可以看下面链接
Java Enum compareTo()用法及代码示例
这里看一下State枚举类
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
也就是说,假设当我们上一个mState为DESTROYED,当前的state为INITIALIZED时,会小于0,执行 backwardPass(lifecycleOwner);方法
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();
// 关注点1:
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());
// 关注点2:
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
大概来讲,就是创建了一个迭代器,然后轮询获取存在mObserverMap中的ObserverWithState
关注点1:observer.mState.compareTo(mState) > 0,这里observer.mState为INITIALIZED,mState=DESTROYED,符合条件,
执行关注点2:observer.dispatchEvent(lifecycleOwner, event);
终于执行到observer.dispatchEvent(lifecycleOwner, event);方法了,这里的observer就是ObserverWithState ,然后再看一下它的dispathEvent方法
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
调用了mLifecycleObserver.onStateChanged(owner, event);将生命周期传递了出去,这样就可以让外部实现了LifeEventObserver的实例观测到生命周期了。