lifecycle通过观察者模式加反射注解模式实习对生命周期的监听。其中实现了LifecycleOwner的为被观察者,实现了LifecycleObserver的微观察者,通过在被观察者中
getLifecycle().addObserver(new TestPresenter());
实现绑定。
一 、LifecycleObserver被观察者
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreateX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStartX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResumeX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPauseX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStopX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestoryX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onANYX(LifecycleOwner owner) {
}
在被观察者中创建对应生命周期的方法,并用OnLifecycleEvent注解,后面在add的时候会通过注解来获取方法。
二、getLifecycle().addObserver绑定流程
关键的方法是createInfo(Class klass, @Nullable Method[] declaredMethods)
在方法中通过反射获取observe的方法
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
然后通过过滤注解得到对应的TYPE和方法名,包装后放入集合中。
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");
}
}
这里要注意下在注解参数为一个的时候是 int callType = CALL_TYPE_NO_ARG;后面会用到。
三、实现了LifecycleOwner的ComponentActivity调用观察者
1、getStateAfter这里有个状态机的概念
2、这个状态机是用的枚举
3、判断CREATED和STARTED当前到底是具体那种生命周期,是通过isAtLeast(@NonNull State state)与上一次状态比大小
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);
}
/**
* Lifecycle states. You can consider the states as the nodes in a graph and
* {@link Event}s as the edges between these nodes.
*/
@SuppressWarnings("WeakerAccess")
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
* right before 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:
*
* - after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
*
- right before {@link android.app.Activity#onStop() onStop} call.
*
*/
CREATED,
/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
*
* - after {@link android.app.Activity#onStart() onStart} call;
*
- right before {@link android.app.Activity#onPause() onPause} call.
*
*/
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;
}
}
四、ObserverWithState和ReflectiveGenericLifecycleObserver
ObserverWithState是一个静态类,在addObsever的时候就创建了mLifecycleObserver,就是通过ReflectiveGenericLifecycleObserver解析注解后返回的对象。在ReflectiveGenericLifecycleObserver中保存了我们add的observe,即mWrapped,和我们通过反射获取的对象mInfo。
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
后面生命周期调用的时候先走的是ObserverWithState的第二个方法dispatchEvent,然后通过
mLifecycleObserver直接调用对应注解的方法
mLifecycleObserver.onStateChanged(owner, event);
一、流程
粘性事件是因为之前setValue的时候,observer未添加到livedata,但是mData值却已经被设置了,等到
LiveDataBus.getInstance().with("data", String.class)
.observe
绑定Observer的时候,会因为 livedata本身监听了Lifecycle owner.getLifecycle().addObserver(wrapper)
从而会走到这里面:
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);
}
最后因为mVersion > mLastVersion没有被return,调用到了最新绑定的observer:
if (observer.mLastVersion >= mVersion) {
return;
}
observer.mLastVersion = mVersion;
observer.mObserver.onChanged((T) mData);
package com.android.jetpackmmi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import com.android.jetpackmmi.single.livedataSingle;
public class MainActivity2 extends AppCompatActivity {
private Button btn2;
private Button btn3;
private static int count = 1;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
livedataSingle.getInstance().with("zsg",String.class)
//ZSG 这里MediatorLiveData 是什么类型Observer<?>就是什么类型
.observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
btn2.setText(s);
}
});
context = this;
/* btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
livedataSingle.getInstance().with("zsg",String.class)
//ZSG 这里MediatorLiveData 是什么类型Observer<?>就是什么类型
.observe((LifecycleOwner) context, new Observer() {
@Override
public void onChanged(String s) {
btn2.setText(s);
}
});
}
});*/
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Handler handler = livedataSingle.getInstance().getActivity();
Message message = handler.obtainMessage();
message.what = 1;
message.obj = String.valueOf(count);
count ++;
handler.sendMessage(message);
}
});
}
}
package com.android.jetpackmmi.single;
import android.app.Activity;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class livedataSingle {
private Map<String, BusMutableLiveData<Object>> bus;
private static volatile livedataSingle single;
private Handler handler;
private livedataSingle() {
bus = new HashMap<>();
}
public static livedataSingle getInstance() {
if (single == null) {
synchronized (livedataSingle.class) {
if (single == null) {
single = new livedataSingle();
}
}
}
return single;
}
//ZSG
//在集合中放入key和匿名的 泛型为Object 的 MutableLiveData
//然后根据传入的类型强转
public synchronized <T> BusMutableLiveData<T> with(String key, Class<T> type) {
if (!bus.containsKey(key)) {
bus.put(key, new BusMutableLiveData<Object>());
}
return ((BusMutableLiveData) bus.get(key));
}
public void setActivity(Handler activity) {
this.handler = activity;
}
public Handler getActivity() {
return handler;
}
public static class BusMutableLiveData<T> extends MutableLiveData{
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {
super.observe(owner, observer);
hook(observer);
}
private void hook(Observer<? super T> observer) {
try{
//1.得到mLastVersion
//获取到LivData的类中的mObservers对象
Class<LiveData> liveDataClass=LiveData.class;
Field mObserversField=liveDataClass.getDeclaredField("mObservers");
mObserversField.setAccessible(true);
//获取到这个成员变量的对象
Object mObserversObject=mObserversField.get(this);
//得到map对象的class对象
Class<?> mObserversClass=mObserversObject.getClass();
//获取到mObservers对象的get方法
Method get=mObserversClass.getDeclaredMethod("get",Object.class);
get.setAccessible(true);
//执行get方法
Object invokeEntry=get.invoke(mObserversObject,observer);
//取到entry中的value
Object observerWraper=null;
if(invokeEntry!=null && invokeEntry instanceof Map.Entry){
observerWraper=((Map.Entry)invokeEntry).getValue();
}
if(observerWraper==null){
throw new NullPointerException("observerWraper is null");
}
//得到observerWraperr的类对象
Class<?> supperClass=observerWraper.getClass().getSuperclass();
Field mLastVersion=supperClass.getDeclaredField("mLastVersion");
mLastVersion.setAccessible(true);
//2.得到mVersion
Field mVersion=liveDataClass.getDeclaredField("mVersion");
mVersion.setAccessible(true);
//3.mLastVersion=mVersion
Object mVersionValue=mVersion.get(this);
mLastVersion.set(observerWraper,mVersionValue);
// mVersion.set(this,-1);
}catch(Exception e){
}
}
}
}
反射mLastVersion 和 mVersion使相等