在研发过程中,解耦是一个永恒的话题。因为解耦可以为后续的维护、功能添加、防内存泄漏、问题查找及更新都带来便利且做到影响最小,但如何进行解耦设计却是一门艺术。今天,我们就来看看google工程师是如何设计LifeCycle的。
我们在很多时候都需要监听Activity的生命周期,比如在页面销毁的时候进行资源的释放、回收。如果让我们自己做的话,想要实现监听其实并不难,对外提供一个接口,在页面生命周期发生变化的时候通过接口告诉外部就可以了。但设想下我们有几十甚至上百个页面的时候,这套设计所需要的接口及其维护成本有多大,其中某个页面生命周期监听发生异常的时候,是否保证这个页面涉及功能修复后其余页面不会出现类似的问题?所幸,google在JetPack中已经为我们设计了这样一套机制,其中关键接口为:LifecycleOwner和LifecycleObserver。嗯,根据这2个接口名称,我想我们不难猜测其采用的设计模式为观察者模式。是的,这2个接口就是LifeCycle的关键,接下来,我们围绕监听是如何添加及监听是如何被调用这两条线展开今天的源码之旅。
先简单的应用下LifeCycle,代码如下:
一个LifecycleObserver观察者类,实现我们监听生命周期的功能
public class BPresenter implements LifecycleObserver {
private final String TAG = this.getClass().getSimpleName();
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate(LifecycleOwner owner){
Log.e(TAG, "onCreate: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart(LifecycleOwner owner){
Log.e(TAG, "onStart: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume(LifecycleOwner owner){
Log.e(TAG, "onResume: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause(LifecycleOwner owner){
Log.e(TAG, "onPause: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop(LifecycleOwner owner){
Log.e(TAG, "onStop: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy(LifecycleOwner owner){
Log.e(TAG, "onDestroy: ");
}
}
然后在对应的页面添加该观察者getLifecycle().addObserver(loginPresenter);
loginPresenter继承了BPresenter 是的,这时候我们运行就可以看到BPresenter 已经监听到了页面生命周期的变化。
ok,代码确实非常简单。那第一个问题是getLifecycle()是什么,不是说好的LifecycleOwner么,怎么没看到呢。别急,我们先围绕观察者是如何被添加的开始第一条线。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner
如果我们围绕着我们所继承的AppCompatActivity往上去追踪的话,不难父类中有ComponentActivity这个类,且其帮我们实现了LifecycleOwner。是的,并不是我们没有用到LifecycleOwner,而是google帮我们实现了而已。那好,getLifecycle()有是什么呢,我们可以点进去。
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
ok ,看到上面的代码我想我们把getLifecycle()理解为注册器比较通俗一点吧,就是专门用来注册观察者的。
getLifecycle().addObserver
public abstract void addObserver(@NonNull LifecycleObserver observer);
开始注册观察者了,Lifecycle只有一个实现类LifecycleRegistry。由于其中牵扯到缓存及支线逻辑判断,我们后续的代码只关注重点代码。
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
ObserverWithState将传进来的LifecycleObserver进行封装,并得到一个ObserverWithState
然后将LifecycleObserver 作键,ObserverWithState作值放进一个Map中
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);
}
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) object;
}
final Class<?> klass = object.getClass();
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
List<Constructor<? extends GeneratedAdapter>> 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 < constructors.size(); i++) {
adapters[i] = createGeneratedAdapter(constructors.get(i), object);
}
return new CompositeGeneratedAdaptersObserver(adapters);
}
return new ReflectiveGenericLifecycleObserver(object);
}
重点关注ReflectiveGenericLifecycleObserver
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
CallbackInfo getInfo(Class klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}
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);
}
}
//重点在这里,便利所有方法,找到有被OnLifecycleEvent注解的方法并进行收集
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 并返回
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
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());
}
}
ok,到这里我们就将观察者成功的添加进来了。其实最终收集的信息是放在mObserverMap这个Map里面的。
那么,我们接下来看下当生命周期发生变化的时候,又是怎么通知到观察者的。我们先找到一个生命周期的变化吧。
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
//重点在这里
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
还是找到androidx.activity.ComponentActivity这个类里来。如果之前看过这个类的就会发现有的代码是在后续的版本添加进来的。
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();
}
}
嗯,这里用了个小技巧,添加了一个空的Fragment用来处理生命周期的分发。如果有了解过Glide的话对这种机制应该比较熟悉。
@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);
}
这是ReportFragment里面几个生命周期函数,可以看到都有调用dispatch这个函数,就是进行对观察者的回调分发的啦。
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);
}
}
}
不管走哪条线,最终调用的是handleLifecycleEvent(event)
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 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);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
到这里不知道可还记得我们前面在添加观察者的时候提到的Map呢,就是mObserverMap这个啦。
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();
}
}
}
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();
}
}
}
这里根据状态机来判断到底该怎么分发,最终都是走observer.dispatchEvent
//这个方法在ObserverWithState
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
还记得我们在添加的时候也封装了ObserverWithState这个类吗,这里面可是有我们的LifecycleObserver的。在回忆下,我们在封装的时候将观察者放进了mLifecycleObserver这里面。
//可还记得我们在进行注解方法收集的时候是在哪的?ReflectiveGenericLifecycleObserver
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
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);
}
}
}
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);
}
}
好吧,到这里基本就结束了。我们已经追到了取出注解的方法并调用,这样我们被注解的方法不就成功收到了生命周期了嘛。
总结一下吧,其实关键就两条线,怎么添加观察者、怎么通知观察者。当然,这中间涉及到了缓存的设计,为什么用到缓存设计其实也是随着现在内存越堆越大,本着不用白不用 啊…呸 其实这也是设计中的一种取舍而已,用空间换时间来提高运行效率。看完这种设计有没有觉得蛮巧妙的?其实如果有看过EventBus源码的应该对这种设计方式不陌生,基本类似吧。
最后在补一张状态机的图,这个比较巧妙,有兴趣的可以研究下。