浅谈Lifecycle的原理,以及liveData在Lifecy
前言扯淡
我们知道jetpack出现给android开发带来很大的便利,尤其是Lifecycle带来的方便,作为一个有志向的码农,就应该了解一下Lifecycle的原理
正题
Lifecycle是生命周期感知型组件是可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。并将变化通知到已注册的观察者。有助于更好地组织代码,让代码逻辑符合生命周期规范,减少内存泄漏,增强稳定性。
Lifecycle整个就是一个观察者模式,来监听activity或者fragment的生命周期。
Lifecycle的分析
- LifecycleOwner(生命周期持有者)接口,activity和fragment的实现接口
该接口只返回了一个Lifecycle对象
public interface LifecycleOwner {
Lifecycle getLifecycle();
}
AppcompatActivity继承了FragmentActivity, FragmentActivity继承了SupportActivity的父类, SupportActivity和 Fragment实现了LifecycleOwner 接口, 所以我们在平常的开发中,使用到AppcompatActivity和Fragment可以使用到LifecycleOwner 。
在SupportActivity和 Fragment, getLifecycle()
返回的是Lifecycle的父类LifecycleRegistry.
Tip
:这边提到一点supportActivity,中是用Fragment (ReportFragment)
的生命周期函数中调用LifecycleRegistry.handleLifecycleEvent()方法改变State。,一个Fragment对应着一个LifecycleRegistry对象。
LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); // this 就是LifecycleOwner的对象
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
- Lifecycle抽象类:
public abstract class Lifecycle {
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
@NonNull
public abstract State getCurrentState();
@SuppressWarnings("WeakerAccess")
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY
}
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
Lifecycle的内部方法说明
方法 | 说明 |
---|---|
addObserver | 添加观察者LifecycleObserver,将LifecycleOwner的状态更改时得到通知 |
removeObserver | 从观察员列表中移除给定的观察员 |
getCurrentState | 返回当前的声明周期状态 |
Event:是lifecycle一共提供了所有的生命周期事件,只要
通过注解进行声明,就能够使LifecycleObserver观察到对应的生命周期事件,activity或者fragment就是通过LifecycleRegistry 的handleLifecycleEvent(Event event)来告知LifecycleRegistry 当前的声明周期事件。
事件 | 说明 |
---|---|
ON_CREATE | 对应Activity的onCreate的事件 |
ON_START | 对应Activity的onStart的事件 |
ON_RESUME | 对应Activity的onResume的事件 |
ON_PAUSE | 对应Activity的onPause的事件 |
ON_STOP | 对应Activity的onStop的事件 |
ON_DESTROY | 对应Activity的onDestroy的事件 |
ON_ANY | 可以匹配任何事件 |
State:状态,是Lifecycle中对应Activity生命周期的一种状态标识
状态 | 说明 |
---|---|
INITIALIZED | 对应Activity的onCreate之前的生命周期 |
DESTROYED | 对应Activity的onDestroy |
CREATED | 对应Activity的onCreate到onStop之间的生命周期 |
STARTED | 对应Activity的onStart到onPause之间的生命周期 |
RESUMED | 对应Activity的onResume |
- LifecycleRegistry实现类:
LifecycleRegistry实现了addObserver方法,添加观察者LifecycleObserver,
public class LifecycleRegistry extends Lifecycle {
private static final String LOG_TAG = "LifecycleRegistry";
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
/** Current state*/
private State mState;
private final WeakReference<LifecycleOwner> mLifecycleOwner;
private int mAddingObserverCounter = 0;
private boolean mHandlingEvent = false;
private boolean mNewEventOccurred = false;
private ArrayList<State> mParentStates = new ArrayList<>();
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
@SuppressWarnings("WeakerAccess")
@MainThread
public void markState(@NonNull State state) {
moveToState(state);
}
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;
}
private State calculateTargetState(LifecycleObserver observer) {
Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
State siblingState = previous != null ? previous.getValue().mState : null;
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
: null;
return min(min(mState, siblingState), parentState);
}
@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) < 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 popParentState() {
mParentStates.remove(mParentStates.size() - 1);
}
private void pushParentState(State state) {
mParentStates.add(state);
}
@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
mObserverMap.remove(observer);
}
@SuppressWarnings("WeakerAccess")
public int getObserverCount() {
return mObserverMap.size();
}
@NonNull
@Override
public State getCurrentState() {
return mState;
}
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE:
case ON_STOP:
return CREATED;
case ON_START:
case ON_PAUSE:
return STARTED;
case ON_RESUME:
return RESUMED;
case ON_DESTROY:
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}
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);
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
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);
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
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));
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) {
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<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
static State min(@NonNull State state1, @Nullable State state2) {
return state2 != null && state2.compareTo(state1) < 0 ? state2 : state1;
}
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);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
}
主要两个内容
1、根据observer和initialState构造ObserverWithState对象statefulObserver,然后将该对象存入mObserverMap,可以简单的把它理解成用来保存观察者的Map。
2、上面我们讲到了SupportActivity也是通过Fragment来向LifecycleRegistry传递声明周期事件,通sync()来更新同步通知mObserverMap 中的所有observer当前的声明周期的事件是处于哪个生命周期阶段。
- Fragment声明周期的对LifecycleRegistry的handleLifecycleEvent(event)调用
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);
}
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);
}
}
}
}
- LifecycleObserver接口:
LifecycleObserver接口( Lifecycle观察者):实现该接口的类,通过注解的方式,可以通过被LifecycleOwner类的addObserver(LifecycleObserver o)方法注册,被注册后,LifecycleObserver便可以观察到LifecycleOwner的生命周期事件。
总结 :整个流程就是Lifecycle(LifecycleRegistry)、LifecycleOwner(Fragment)、LifecycleObserver三者之间的关系:Fragment生命周期--通过handleLifecycleEvent(event)将生命周期通知给 LifecycleRegistry,LifecycleRegistry通知观察者LifecycleObserver当前生命周期
。livedata 就是一个很好的例子
- 举个栗子:
先自定义LifecycleObserver
public interface IObserver extends LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreate(@NotNull LifecycleOwner owner);
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy(@NotNull LifecycleOwner owner);
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onLifecycleChanged(@NotNull LifecycleOwner owner,
@NotNull Lifecycle.Event event);
}
在activity中添加往Lifecycle中添加observer观察者对象
public class MainActivity extends AppCompatActivity { //AppCompatActivity 是就是LifecycleOwner
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("tag", "onCreate" + this.getClass().toString());
setContentView(R.layout.activity_main);
MyObserver observer = new MyObserver();
getLifecycle().addObserver(observer );//添加LifecycleObserver
}
class MyObserver implements IObserver {
@Override
public void onLifecycleChanged(@NotNull LifecycleOwner owner, @NotNull Lifecycle.Event event) {
}
@Override
public void onCreate(@NotNull LifecycleOwner owner) {
Log.d("MyObserver ", "onCreate" + this.getClass().toString());
}
@Override
public void onDestroy(@NotNull LifecycleOwner owner) {
Log.d("MyObserver ", "onDestroy" + this.getClass().toString());
}
}
@Override
protected void onDestroy() {
Log.d("tag", "onDestroy" + this.getClass().toString());
super.onDestroy();
}
}
上面的demo很简单,就是在AppcompatActivity中通过getLifecycle()添加一个观察一个观察者,然后activity的生命周期变动后,Lifecycle通知观察者。
LiveData的Observe方法
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
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);
}
- 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);
}
}
GenericLifecycleObserver其实就是 LifecycleObserver 的子类
public interface GenericLifecycleObserver extends LifecycleObserver {
/**
* Called when a state transition event happens.
*
* @param source The source of the event
* @param event The event
*/
void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}
也就是说liveData通过observe的方法传进来LifecycleOwner参数, 创建一个LifecycleBoundObserver 就是一个观察者,被添加到Lifecycle中,进行观察activity或者fragment的生命周期。其实LiveData其他添加观察者到Lifecycle的管理者。
参考& 感谢
https://blog.csdn.net/u013651026/article/details/80822441
https://blog.csdn.net/zhuzp_blog/article/details/78871374
https://www.jianshu.com/p/2c9bcbf092bc