目录
Jetpack之Lifecyle原理分析
Jetpack之LiveData原理分析
Jetpack之ViewMdel原理分析
Jetpack之LiveData+ViewMde+Flow+Retrofit架构设计
介绍
Lifecycle 是一个类它唯一的实现类是LifecycleRegistry,Lifecycle用于存储和有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态。
生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。这些组件有助于您写出更有条理且往往更精简的代码,这样的代码更易于维护。
一种常见的模式是在 Activity 和 Fragment 的生命周期方法中实现依赖组件的操作。但是,这种模式会导致代码条理性很差而且会扩散错误。通过使用生命周期感知型组件,您可以将依赖组件的代码从生命周期方法移入组件本身中。
当然你是可以让任何对象能够让Lifecycle感知它的生命周期,比如:Dialog它本身是不具有让Lifecycle感知它的生命周期,但是我们可以通过自定义让Dialog拥有这种能力的,后面我们将结合源码的形式去讲解这种方式,也许你会对Lifecycle的原理有大概的了解。
androidx.lifecycle 包提供了可用于构建生命周期感知型组件的类和接口 - 这些组件可以根据 Activity 或 Fragment 的当前生命周期状态自动调整其行为。
实际上 Lifecyle是一个接口他有一个唯一实现类LifecycleRegistry,LifecycleRegistry封装了LifecycleOwner和LifecycleObserver以及处理分发生命周期。
简单使用
任何类都可以通过向其方法添加注解来监控组件的生命周期状态。然后,您可以通过调用 Lifecycle 类的 addObserver() 方法并传递观察者的实例来添加观察者,其实最终是注册到LifecycleRegistry生命周期表中
class MyObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPauser() { }
}
myLifecycleOwner.getLifecycle().addObserver(MyObserver())
在上面的示例中,myLifecycleOwner
对象实现了 LifecycleOwner
接口,我们将在接下来的部分中对该接口进行说明。
LifecycleOwner
LifecycleOwner
是单一方法接口,表示类具有Lifecycle
。它具有一个方法(即getLifecycle()
),该方法必须由代表或具有一生命周期的类实现,如Activity和Fragment,LifecycleOwner
翻译过来就是生命周期持有者或者提供者,所以LifecycleOwner
代表的是一个实现LifecycleOwner的类具有生命周期,但是仅仅实现了LifecycleOwner是不够的,因为你的把LifecycleOwner注册到LifecycleRegistry
,LifecycleRegistry翻译过来就是生命周期注册表,需要将LifecycleOwner注册到LifecycleRegistry中有该类对生命周期进行分发生命周期事件。如果你想尝试管理整个应用进程的生命周期,请参阅ProcessLifecycleOwner
。此接口从各个类(如
Fragment
和AppCompatActivity
)抽象化Lifecycle
的所有权,并允许编写与这些类搭配使用的组件。任何自定义应用类均可实现LifecycleOwner
接口。实现
LifecycleObserver
的组件可与实现LifecycleOwner
的组件无缝协同工作,因为LifecycleOwner
可以提供生命周期,而观察者可以注册以观察生命周期。
实现自定义 LifecycleOwner
Fragment 和 Activity 已实现 LifecycleOwner
接口。
如果我们有一个自定义类并希望使其成为 LifecycleOwner
,您可以使用 LifecycleRegistry 类,但需要将事件转发到该类,比如前面说到让Dialog有用让Lifecucle感知它的生命周期,如以下代码示例中所示:。
class DialogLifeCycle(context: Context, themeResId: Int) : Dialog(context, themeResId),LifecycleOwner {
private val mDispatcher by lazy { LifecycleDispatcher(this) }
override fun getLifecycle(): Lifecycle {
return mDispatcher.getLifecycle()
}
override fun onCreate(savedInstanceState: Bundle?) {
mDispatcher.onDialogPreSuperOnCreate()
super.onCreate(savedInstanceState)
}
override fun onStart() {
mDispatcher.onDialogPreSuperOnStart()
mDispatcher.onDialogPreSuperResume()
super.onStart()
}
override fun onStop() {
mDispatcher.onDialogPreSuperPause()
mDispatcher.onDialogPreSuperOnStop()
mDispatcher.onDialogPreSuperOnDestroy()
super.onStop()
}
}
########LifecycleOwner帮助类
class LifecycleDispatcher(provider: LifecycleOwner) {
private var mRegistry: LifecycleRegistry = LifecycleRegistry(provider)
private var mHandler: Handler = Handler()
private lateinit var mLastDispatchRunnable: DispatchRunnable
private fun postDispatchRunnable(event: Lifecycle.Event) {
if (this::mLastDispatchRunnable.isInitialized) {
mLastDispatchRunnable.run()
}
mLastDispatchRunnable = DispatchRunnable(mRegistry, event)
mHandler.postAtFrontOfQueue(mLastDispatchRunnable)
}
fun onDialogPreSuperOnCreate() {
postDispatchRunnable(Lifecycle.Event.ON_CREATE)
onDialogPreSuperAny()
}
fun onDialogPreSuperOnStart() {
postDispatchRunnable(Lifecycle.Event.ON_START)
onDialogPreSuperAny()
}
fun onDialogPreSuperResume() {
postDispatchRunnable(Lifecycle.Event.ON_RESUME)
onDialogPreSuperAny()
}
fun onDialogPreSuperPause() {
postDispatchRunnable(Lifecycle.Event.ON_PAUSE)
onDialogPreSuperAny()
}
fun onDialogPreSuperOnDestroy() {
postDispatchRunnable(Lifecycle.Event.ON_DESTROY)
onDialogPreSuperAny()
}
fun onDialogPreSuperOnStop() {
postDispatchRunnable(Lifecycle.Event.ON_STOP)
onDialogPreSuperAny()
}
fun onDialogPreSuperAny() {
postDispatchRunnable(Lifecycle.Event.ON_ANY)
}
fun getLifecycle(): Lifecycle {
return mRegistry
}
class DispatchRunnable(
private val mRegistry: LifecycleRegistry,
private val mEvent: Lifecycle.Event,
private var mWasExecuted: Boolean = false
) : Runnable {
override fun run() {
if (!mWasExecuted) {
mRegistry.handleLifecycleEvent(mEvent)
mWasExecuted = true
}
}
}
}
然后我们通过 lifecycle.addObserver(MyLifeCycle())方法将生命周期观察这注册给lifecycle也就是LifecycleRegistry,这样我们在MyLifeCycle就能感知Dialog的生命周期变化。
源码分析原理
在lifecycle.addObserver(MyLifeCycle())将生命周期观察这注册给lifecycle,那我们从这里开始:
#######MyLifeCycle
class MyLifecycleObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
LogUtil.error("MyLifeCycle onCreate")
}
}
我们定义的了MyLifecycleObserver 并让他实现LifecycleObserver ,最后编译期会生成代码,如下:
public class MyLifecycleObserver_LifecycleAdapter implements GeneratedAdapter {
final MyLifeCycle mReceiver;
MyLifeCycle_LifecycleAdapter(MyLifeCycle receiver) {
this.mReceiver = receiver;
}
public void callMethods(LifecycleOwner owner, Event event, boolean onAny, MethodCallsLogger logger) {
boolean hasLogger = logger != null;
if (!onAny) {
if (event == Event.ON_CREATE) {
if (!hasLogger || logger.approveCall("onCreate", 1)) {
this.mReceiver.onCreate();
}
}
}
}
}
在生成MyLifecycleObserver_LifecycleAdapter 类的callMethods方法中会调用我们的MyLifecycle的方法 this.mReceiver.onCreate(),那么callMethods方法在哪触发呢?我么看看LifecycleRegistry .addObserver方法:
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//1
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//2
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//省略...........................
}
上面代码主要是将observer保存在mObserverMap中,并计算当前的状态。接下我们看看触发生命周期的方法,首先我们定义了LifecycleRegistry 并使用 LifecycleRegistry .handleLifecycleEvent(mEvent)方法对生命周期的事件进行分发,代码如下:
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
方法很简单,我们主要看moveToState,意思是改变状态,代码如下:
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;
}
这个方法比较简单,主要是对状态进行判断,接着我么来看看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);//1
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);//2
}
}
mNewEventOccurred = false;
}
在sync方法中我们主要看backwardPass方法的实现:
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);//1
popParentState();
}
}
}
在我注释1处,看到了 observer.dispatchEvent(lifecycleOwner, event),这个方法处于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 = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
在ObserverWithState 的构造方法中我们主要看看mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer)这行代码,实现如下:
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object 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);
}
在lifecycleEventObserver方法中object参数就是我们定义实现了LifecycleObserver接口的MyLifecycle对象,并且通过这个对象去拿到构造方法,实际上是通过拼接_LifecycleAdapter拿到MyLifeCycle_LifecycleAdapter 对象,并创建了GeneratedAdapter对象并把MyLifecycle对象当做参数传进去。
在上MyLifecycle生成类的代码:
public class MyLifeCycle_LifecycleAdapter implements GeneratedAdapter {
final MyLifeCycle mReceiver;
MyLifeCycle_LifecycleAdapter(MyLifeCycle receiver) {
this.mReceiver = receiver;
}
public void callMethods(LifecycleOwner owner, Event event, boolean onAny, MethodCallsLogger logger) {
boolean hasLogger = logger != null;
if (!onAny) {
if (event == Event.ON_CREATE) {
if (!hasLogger || logger.approveCall("onCreate", 1)) {
this.mReceiver.onCreate();
}
}
}
}
}
最后在ObserverWithState.dispatchEvent方法中调用了 mLifecycleObserver.onStateChanged(owner, event)方法,也就是定义的MyLifecycle类生成的MyLifeCycle_LifecycleAdapter 类的onStateChanged方法,最终会调用我们的MyLifecycle的onCreate()方法,最后在看一下具体的流程图:
Lifecycle的原理比较简单,调用过程也比较简单。但使用时需要注意以下几点:
- Lifecycle有状态倒灌过程,也就是在任意生命周期中注册LifecycleObserver,这个LifecycleObserver会把前面的生命周期回调都执行一遍,直到和注册时的生命周期状态同步。
- 在Activity/Fragment重写生命周期方法时,必须调用父类的相应方法,因为Lifecycle的生命周期分发在父类的相应生命周期方法中。
总结
首先
LifeCycle
的实现类LifecycleRegistry
封装了LifecycleObserver
、LifecycleOwner
以及组件的生命周期的分发逻辑,以Activity为例,那么Activity生命周期是怎么分发到LifecycleRegistry的?首先在ComponentActivity
的onCreate方法中会调用 ReportFragment.injectIfNeededIn(this)方法,在injectIfNeededIn中将ComponentActivity
的生命周期回调,并将ReportFragment注册到该Activity中监听Activity的生命周期,当Activity的生命周期状态发生改变会调用ReportFragment的dispatch将生命周期分发给LifecycleRegistry.handleLifecycleEvent(event)
,最终会通过LifecycleRegistry将生命周期分发到LifecycleObserver中。以Activity为例,Activity实现了LifecycleOwner的getLifecycle的方法并返回的是LifeCycle 表示Activity代理生命周期的接口,而LifeCycle的实现类LifecycleRegistry分装了生命周期分发的所有逻辑 ,当Activity生命周期发生变化就会通过LifecycleRegistry.handleLifecycleEvent(event)进行分发到通过Lifecycle.addObserver添加的LifecycleObserver的监听生命周期方法上,第一种是注解生成,另一种是LifecycleEventObserver。
Activity虽然实现了LifecycleOwner接口,仅仅只是实现了LifecycleOwner的getLifeCycle方法,该方法返回的是LifeCycle实现类LifecycleRegistry,通过源码可知LifecycleRegistry封装了所有生命周期分发的逻辑,并在Activity的onCreate中通过添加一个ReportFragment类监听Activity生命周期,当Activity生命周期发生变化就会通过LifecycleRegistry.handleLifecycleEvent(event)进行分发到通过Lifecycle.addObserver添加的LifecycleObserver的监听生命周期方法上。