当使用MVVM框架时,ViewModel会实现LifecycleObserver接口类,使用OnLifecycleEvent注解声明当生命周期发生改变时会回调的方法,从而在ViewModel层也可以监听到生命周期。那么它是如何实现的?
首先我们要了解一些基础相关的知识点
1.LifecycleObserver:是一个接口,没有声明任何抽象方法,就是为了标识其子类实现是LifecycleObserver这一类型;也是一个观察者,观察Activity/Fragment的生命周期状态改变
public interface LifecycleObserver {
}
Lifecycle:是一个抽象类,可用于添加/移除LifecycleObserver;使用Event枚举来定义生命周期标识符;使用State枚举来定义Activity/Fragment的状态
public abstract class Lifecycle {
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@NonNull
AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
/**
* 添加一个LifecycleObserver
* @param observer
*/
@MainThread//指定该方法要在主线程 若在异步线程则抛异常
public abstract void addObserver(@NonNull LifecycleObserver observer);
/**
* 移除一个LifecycleObserver
* @param observer
*/
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
/**
* 获取当前状态
* @return
*/
@MainThread
@NonNull
public abstract State getCurrentState();
/**
* 生命周期事件
*/
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 androidx.lifecycle.Lifecycle.Event Event} constant that can be used to match all events.
*/
ON_ANY
}
public enum State {
/**
* Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
* any more events. For instance, for an {@link android.app.Activity}, this state is reached
* <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
*/
DESTROYED,
/**
* Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
* the state when it is constructed but has not received
* {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
*/
INITIALIZED,
/**
* Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
* <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
* </ul>
*/
CREATED,
/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onStart() onStart} call;
* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
* </ul>
*/
STARTED,
/**
* Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached after {@link android.app.Activity#onResume() onResume} is called.
*/
RESUMED;
/**
* Compares if this State is greater or equal to the given {@code state}.
*
* @param state State to compare with
* @return true if this State is greater or equal to the given {@code state}
*/
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
OnLifecycleEvent:是一个注解类,用于注解一个方法,其返回值是Lifecycle.Event
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
Lifecycle.Event value();
}
IBaseViewModel:实现LifecycleObserver接口,定义了当Activity/Fragment的生命周期发生改变时会被调用的方法。(注意:需要使用OnLifecycleEvent注解声明)
interface IBaseViewModel implement LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreate()
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void onStart()
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume()
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void onPause()
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onStop()
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy()
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onAny(owner: LifecycleOwner, event: Lifecycle.Event)
}
LifecycleOwner:是一个接口类,用于获取Lifecycle对象,在ComponentActivity/Fragment中实现类该接口类
interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
接下来我们看一下调用流程
1.首先让BaseViewModel实现IBaseViewModel接口,那么BaseViewModel也是LifecycleObserver的子类
abstract class BaseViewModel<M : BaseModel> exdends AndroidViewModel implement IBaseViewModel {
}
2.在Activity/Fragment中调用该方法将BaseViewModel作为LifecycleObserver被添加到观察者列表中
getLifecycle().addObserver(LifecycleObserver)
3.我们可以看到在Fragment/ComponentActivity中会创建LifecycleRegistry对象,通过getLifecycle()获取的就是LifecycleRegistry,而LifecycleRegistry将会将LifecycleObserver添加到观察者列表中
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
ViewModelStoreOwner {
LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
.......
}
public class ComponentActivity extends Activity
implements LifecycleOwner, KeyEventDispatcher.Component {
LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
.......
}
4.在ComponentActivity的onCreate()中调用 ReportFragment.injectIfNeededIn(this),即为Activity增加了一个ReportFragment,这个fragment没有其它操作,就是用来同步Activity生命周期的,在各个生命周期方法中通过调用dispatch()将当前生命周期状态通知给 LifecycleRegistry的观察者列表,而观察者就是LifecycleObserver,它里面有我们注解的生命周期方法,而LifecycleRegistry会通过反射获取注解的方法,之后根据对应的生命周期状态调用对应的方法,从而使我们的ViewModel(LifecycleObserver的子类)也能够同步Activity的生命周期状态,那么LifecycleRegistry到底如何操作的?
public class ComponentActivity extends Activity
implements LifecycleOwner, KeyEventDispatcher.Component {
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
}
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
public static void injectIfNeededIn(Activity activity) {
// ProcessLifecycleOwner should always correctly work and some activities may not extend
// FragmentActivity from support lib, so we use framework fragments for activities
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();
}
}
static ReportFragment get(Activity activity) {
return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
REPORT_FRAGMENT_TAG);
}
private ActivityInitializationListener mProcessListener;
private void dispatchCreate(ActivityInitializationListener listener) {
if (listener != null) {
listener.onCreate();
}
}
private void dispatchStart(ActivityInitializationListener listener) {
if (listener != null) {
listener.onStart();
}
}
private void dispatchResume(ActivityInitializationListener listener) {
if (listener != null) {
listener.onResume();
}
}
@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);
}
}
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
}
5.LifecycleRegistry继承于Lifecycler,重写了addObserver()/removeObserver(),添加和移除观察者;内部有一个内部类ObserverWithState,存储LifecycleObserver以及LifecycleObserver的状态,它会通过LifecycleObserver的子类类型来判断是那一种GenericLifecycleObserver,默认返回ReflectiveGenericLifecycleObserver,而ReflectiveGenericLifecycleObserver会通过反射获取所有的注解OnLifecycleEvent的方法并将其存储起来;FastSafeIterableMap是以LifecycleObserver(我们传进来的ViewModel,实现了LifecycleObserver)为key,以存储LifecycleObserver和状态的ObserverWithState为value,其优势是能在遍历的过程中也能进行添加和移除操作;mLifecycleOwner其实是Activity/Fragment的弱引用,主要判断Activity/Fragment是否被销毁,若被销毁将不再进行后续操作;mState存储当前Activity/Fragment的状态 其顺序为DESTROYED < INITIALIZED < CREATED < STARTED < RESUMED;mHandlingEvent用来判断是否正在同步状态,true:正在同步所有观察者的状态 false:没有同步所有观察者的状态;mAddingObserverCounter:当添加一个观察者的时候加1 添加完成后减1;mNewEventOccurred:当正在同步或者添加观察者的时候为true 默认为false,当为true时会中断当前的同步操作,之后根据最后的状态同步所欲观察者的状态
public class LifecycleRegistry extends Lifecycle {
private static final String LOG_TAG = "LifecycleRegistry";
/**
* Custom list that keeps observers and can handle removals / additions during traversal.
*
* Invariant: at any moment of time for observer1 & observer2:
* if addition_order(observer1) < addition_order(observer2), then
* state(observer1) >= state(observer2),
*/
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
/**
* Current state
*/
private State mState;
/**
* The provider that owns this Lifecycle.
* Only WeakReference on LifecycleOwner is kept, so if somebody leaks Lifecycle, they won't leak
* the whole Fragment / Activity. However, to leak Lifecycle object isn't great idea neither,
* because it keeps strong references on all other listeners, so you'll leak all of them as
* well.
*/
private final WeakReference<LifecycleOwner> mLifecycleOwner;
private int mAddingObserverCounter = 0;
private boolean mHandlingEvent = false;
private boolean mNewEventOccurred = false;
// we have to keep it for cases:
// void onStart() {
// mRegistry.removeObserver(this);
// mRegistry.add(newObserver);
// }
// newObserver should be brought only to CREATED state during the execution of
// this onStart method. our invariant with mObserverMap doesn't help, because parent observer
// is no longer in the map.
private ArrayList<State> mParentStates = new ArrayList<>();
/**
* Creates a new LifecycleRegistry for the given provider.
* <p>
* You should usually create this inside your LifecycleOwner class's constructor and hold
* onto the same instance.
*
* @param provider The owner LifecycleOwner
*/
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
/**
* Moves the Lifecycle to the given state and dispatches necessary events to the observers.
*
* @param state new state
*/
@SuppressWarnings("WeakerAccess")
@MainThread
public void markState(@NonNull State state) {
moveToState(state);
}
/**
* Sets the current state and notifies the observers.
* <p>
* 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;
}
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) {
// we consciously decided not to send destruction events here in opposition to addObserver.
// Our reasons for that:
// 1. These events haven't yet happened at all. In contrast to events in addObservers, that
// actually occurred but earlier.
// 2. There are cases when removeObserver happens as a consequence of some kind of fatal
// event. If removeObserver method sends destruction events, then a clean up routine becomes
// more cumbersome. More specific example of that is: your LifecycleObserver listens for
// a web connection, in the usual routine in OnStop method you report to a server that a
// session has just ended and you close the connection. Now let's assume now that you
// lost an internet and as a result you removed this observer. If you get destruction
// events in removeObserver, you should have a special case in your onStop method that
// checks if your web connection died and you shouldn't try to report anything to a server.
mObserverMap.remove(observer);
}
/**
* The number of observers.
*
* @return The number of observers.
*/
@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.在addObserver()中会将LifecycleObserver以及状态封装到ObserverWithState中,然后存到FastSafeIterableMap,在添加之后若当前界面的状态和 LifecycleObserver(ViewModel)的状态不一样,将会更新当前LifecycleObserver(ViewModel)的状态。最后若当前没有同步状态操作,那么将调用sync()进行所有观察者的同步操作
- 2.在removeObserver()中直接从FastSafeIterableMap移除对应的LifecycleObserver
- 3.在getCurrentState()中获取当前Activity/Fragment的生命周期状态
- 4.handleLifecycleEvent()在ReportFragment中被调用,通知所有观察者生命周期改变
- 5.sync() while循环查看所有观察者的状态是否和当前的状态相同,若相同,表示所有的观察者的状态都是最新的;若不相同,则需要同步所有的观察者的的状态,遍历观察者,若观察者的状态小于当前状态,则状态需要向前移动,会调用forwardPass();若观察者的状态大于当前状态,则状态需要向后移动,会调用backwardPass()
- 6.forwardPass():当有观察者的状态小于当前状态时会被调用,将观察者的状态变成下一个状态,之后调用ObserverWithState的dispatchEvent()触发对应LifecycleObserver的注解事件方法
- 7.backwardPass():当有观察者的状态大于当前状态时会被调用,将观察者的状态变成上一个状态,之后调用ObserverWithState的dispatchEvent()触发对应LifecycleObserver的注解事件方法
- 8.dispatchEvent():用来修改LifecycleObserver的状态,会调用ReflectiveGenericLifecycleObserver的onStateChanged(),因ReflectiveGenericLifecycleObserver通过ClassesInfoCache存储了所有的注解方法,当调用该方法时会获取所有对应的注解事件的方法集合,然后通过反射调用对应的方法,那么ViewModel中的使用OnLifecycleEvent注解的方法被调用
7.ReflectiveGenericLifecycleObserver是GenericLifecycleObserver的子类,当LifecycleObserver被封装到ObserverWithState时会通过Lifecycling.getCallback(observer)获取一个GenericLifecycleObserver,若observer不是FullLifecycleObserver/GenericLifecycleObserver/SingleGeneratedAdapterObserver/CompositeGeneratedAdaptersObserver,那么将使用ReflectiveGenericLifecycleObserver。 当Activity/Fragment的状态发生改变通知ViewModel时,最终会通过它来通过反射调用方法来实现通知
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
//LifecycleObserver
private final Object mWrapped;
private final ClassesInfoCache.CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
说明
- 1.实现GenericLifecycleObserver接口类,重写了onStateChanged()方法
- 2.在构造函数中持有LifecycleObserver(ViewModel)的引用,同时通过ClassesInfoCache.sInstance.getInfo()获取LifecycleObserver所有的使用了OnLifecycleEvent注解声明的方法信息
- 3.当Activity/Fragment的生命周期发生了改变,将会调用ObserverWithState的dispatchEvent(),而在dispatchEvent()中会调用onStateChanged(),那么最终ClassesInfoCache会根据事件获取对应事件的所有方法,最后通过反射调用触发这些方法
8.ClassesInfoCache主要用来收集Class中所有的使用OnLifecycleEvent的方法,并根据事件类型,来触发对应事件类型的方法
class ClassesInfoCache {
static ClassesInfoCache sInstance = new ClassesInfoCache();
private static final int CALL_TYPE_NO_ARG = 0;
private static final int CALL_TYPE_PROVIDER = 1;
private static final int CALL_TYPE_PROVIDER_WITH_EVENT = 2;
private final Map<Class, CallbackInfo> mCallbackMap = new HashMap<>();
private final Map<Class, Boolean> mHasLifecycleMethods = new HashMap<>();
boolean hasLifecycleMethods(Class klass) {
if (mHasLifecycleMethods.containsKey(klass)) {
return mHasLifecycleMethods.get(klass);
}
Method[] methods = getDeclaredMethods(klass);
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation != null) {
// Optimization for reflection, we know that this method is called
// when there is no generated adapter. But there are methods with @OnLifecycleEvent
// so we know that will use ReflectiveGenericLifecycleObserver,
// so we createInfo in advance.
// CreateInfo always initialize mHasLifecycleMethods for a class, so we don't do it
// here.
createInfo(klass, methods);
return true;
}
}
mHasLifecycleMethods.put(klass, false);
return false;
}
private Method[] getDeclaredMethods(Class klass) {
try {
return klass.getDeclaredMethods();
} catch (NoClassDefFoundError e) {
throw new IllegalArgumentException("The observer class has some methods that use "
+ "newer APIs which are not available in the current OS version. Lifecycles "
+ "cannot access even other methods so you should make sure that your "
+ "observer classes only access framework classes that are available "
+ "in your min API level OR use lifecycle:compiler annotation processor.", e);
}
}
CallbackInfo getInfo(Class klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}
private void verifyAndPutHandler(Map<MethodReference, Lifecycle.Event> handlers,
MethodReference newHandler, Lifecycle.Event newEvent, Class klass) {
Lifecycle.Event event = handlers.get(newHandler);
if (event != null && newEvent != event) {
Method method = newHandler.mMethod;
throw new IllegalArgumentException(
"Method " + method.getName() + " in " + klass.getName()
+ " already declared with different @OnLifecycleEvent value: previous"
+ " value " + event + ", new value " + newEvent);
}
if (event == null) {
handlers.put(newHandler, newEvent);
}
}
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
Class superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
if (superclass != null) {
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
Lifecycle.Event event = annotation.value();
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supported only for ON_ANY value");
}
}
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
MethodReference methodReference = new MethodReference(callType, method);
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
@SuppressWarnings("WeakerAccess")
static class CallbackInfo {
final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;
CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
mHandlerToEvent = handlerToEvent;
mEventToHandlers = new HashMap<>();
for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
Lifecycle.Event event = entry.getValue();
List<MethodReference> methodReferences = mEventToHandlers.get(event);
if (methodReferences == null) {
methodReferences = new ArrayList<>();
mEventToHandlers.put(event, methodReferences);
}
methodReferences.add(entry.getKey());
}
}
@SuppressWarnings("ConstantConditions")
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
target);
}
private static void invokeMethodsForEvent(List<MethodReference> handlers,
LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
if (handlers != null) {
for (int i = handlers.size() - 1; i >= 0; i--) {
handlers.get(i).invokeCallback(source, event, mWrapped);
}
}
}
}
@SuppressWarnings("WeakerAccess")
static class MethodReference {
final int mCallType;
final Method mMethod;
MethodReference(int callType, Method method) {
mCallType = callType;
mMethod = method;
mMethod.setAccessible(true);
}
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
//noinspection TryWithIdenticalCatches
try {
switch (mCallType) {
case CALL_TYPE_NO_ARG:
mMethod.invoke(target);
break;
case CALL_TYPE_PROVIDER:
mMethod.invoke(target, source);
break;
case CALL_TYPE_PROVIDER_WITH_EVENT:
mMethod.invoke(target, source, event);
break;
}
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to call observer method", e.getCause());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MethodReference that = (MethodReference) o;
return mCallType == that.mCallType && mMethod.getName().equals(that.mMethod.getName());
}
@Override
public int hashCode() {
return 31 * mCallType + mMethod.getName().hashCode();
}
}
}
说明
- 1.CALL_TYPE_NO_ARG: 标识符,表示通过反射调用方法时不传递参数
- 2.CALL_TYPE_PROVIDER:标识符,表示通过反射调用方法时传递一个参数
- 3.CALL_TYPE_PROVIDER_WITH_EVENT:标识符,表示通过反射调用方法时传递两个参数
- 4.mHasLifecycleMethods:map集合,以class为key,以boolean为value,标识这个class中是否含有OnLifecycleEvent注解的方法
- 5.mCallbackMap:map集合,以class为key,以存储了class相关信息的CallbackInfo为value,它包含了这个class所有的OnLifecycleEvent注解的方法
- 6.MethodReference是一个静态内部类,它存储OnLifecycleEvent注解的方法以及调用时的传参类型,其中invokeCallback()方法实现了Method的反射调用
- 7.CallbackInfo是一个静态内部类,当我们把所有OnLifecycleEvent注解的方法获取到后进行整理,将同一个事件的方法,放入一个集合中,并以事件为key,以对应方法集合为value存储到map中
- 8.invokeCallbacks():调用invokeMethodsForEvent()触发对应的事件,但同时我们可以看到,调用任何一个事件都会触发ON_ANY事件
- 9.invokeMethodsForEvent():根据事件找到对应事件的方法集合,然后遍历集合所有的方法进行调用
总结
- 1.LifecycleObserver是一个接口类,没有定义任何方法,它表示是Activity/Fragment生命周期变化的观察者
- 2.自定义的ViewModel实现了IBaseViewModel接口类,而IBaseViewModel实现了LifecycleObserver,并定义了使用OnLifecycleEvent注解声明的方法,那么ViewModel就是一个LifecycleObserver。那么当Activity/Fragment的生命周期发生改变时,如何被触发对应的方法呢?那么就要借助LifecycleRegistry
- 3.LifecycleRegistry是Lifecycle的子类,它在Activity/Fragment中被创建,它用来添加/移除生命周期变化观察者,在生命周期发生改变后同步生命周期状态
- 4.Activity会添加一个ReportFragment,这个framgent没有界面,不做其他操作 ,只是用来同步生命周期的,当fragment在不同的生命周期状态时,将会调用LifecycleRegistry的handleLifecycleEvent()来通知观察者
- 5.Fragment会有一个FragmentManager的子类FragmentManagerImpl,用于对Fragment进行管理,而在Fragment的生命周期状态发生改变时会调用FragmentManagerImpl的moveToState(),在方法中会根据当前Fragment的State触发不同的操作,但最终都会调用 mLifecycleRegistry.handleLifecycleEvent(Event)来通知观察者
- 6.LifecycleRegistry的addObserver()用来添加观察者,并将其对应的状态一起封装到ObserverWithState中,之后同步添加的观察者状态,最后调用sync()将当前最新状态同步到所有的观察者中
- 7.LifecycleRegistry的removeObserver()用来移除观察者
- 8.ObserverWithState是LifecycleRegistry的一个静态内部类,它包含一个LifecycleObserver以及对应的状态信心,同时通过Lifecycling.getCallback(observer)得到一个GenericLifecycleObserver,最终是ReflectiveGenericLifecycleObserver
- 9.ReflectiveGenericLifecycleObserver是GenericLifecycleObserver的子类,它会通过反射获取LifecycleObserver中所有使用OnLifecycleEvent注解声明的方法,之后将其归类,将所有相同注解事件放入集合,以Event为key,以集合为value,存入到map中
- 10.当Activity/Fragment的进入不同生命周期时会调用LifecycleRegistry的handleLifecycleEvent(),之后调用sync()遍历所有的观察者列表,将当前状态传给观察者的包装对象ObserverWithState,ObserverWithState会触发dispatchEvent(),在dispatchEvent()中调用ReflectiveGenericLifecycleObserver的onStateChanged(),而在onStateChanged()中会调用ClassesInfoCache.CallbackInfo的invokeCallbacks(),最后会根据事件Event获取到对应的方法集合,通过反射触发方法,这样就完成当Acitvity/Fragment的生命周期发生改变时,ViewModel(LifecycleObserver)中使用OnLifecycleEvent注解的方法会被触发