1、什么是Lifecycle
Lifecycle,顾名思义,是用于帮助开发者管理Activity和Fragment 的生命周期,它是LiveData和ViewModel的基础。
1.1 为什么引入Lifecycle
我们在处理Activity或者Fragment组件的生命周期相关时,不可避免会遇到这样的问题: 我们在Activity的onCreate()中初始化某些成员(比如MVP架构中的Presenter,或者AudioManager、MediaPlayer等),然后在onStop中对这些成员进行对应处理,在onDestroy中释放这些资源,这样导致我们的代码也许会像这样:
class MyPresenter{
public MyPresenter() {
}
void create() {
}
void destroy() {
}
}
class MyActivity extends AppCompatActivity {
private MyPresenter presenter;
public void onCreate(...) {
presenter= new MyPresenter ();
presenter.create();
}
public void onDestroy() {
super.onDestroy();
presenter.destory();
}
}
代码没有问题,关键问题是,实际生产环境中 ,这样的代码会非常复杂,你最终会有太多的类似调用并且会导致 onCreate() 和 onDestroy() 方法变的非常臃肿。
解决方案:
Lifecycle 是一个类,它持有关于组件(如 Activity 或 Fragment)生命周期状态的信息,并且允许其他对象观察此状态。 我们只需要2步:
- Prestener继承LifecycleObserver接口
public interface IPresenter 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);
}
public class BasePresenter implements IPresenter {
private static final String TAG = "com.qingmei2.module.base.BasePresenter";
@Override
public void onLifecycleChanged(@NotNull LifecycleOwner owner, @NotNull Lifecycle.Event event) {
}
@Override
public void onCreate(@NotNull LifecycleOwner owner) {
Log.d("tag", "BasePresenter.onCreate" + this.getClass().toString());
}
@Override
public void onDestroy(@NotNull LifecycleOwner owner) {
Log.d("tag", "BasePresenter.onDestroy" + this.getClass().toString());
}
}
这里我直接将我想要观察到Presenter的生命周期事件都列了出来,然后封装到BasePresenter 中,这样每一个BasePresenter 的子类都能感知到Activity容器对应的生命周期事件,并在子类重写的方法中,对应相应行为。 - 在Activity/Fragment容器中添加Observer:
public class MainActivity extends AppCompatActivity {
private IPresenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("tag", "onCreate" + this.getClass().toString());
setContentView(R.layout.activity_main);
mPresenter = new MainPresenter(this);
getLifecycle().addObserver(mPresenter);
}
@Override
protected void onDestroy() {
Log.d("tag", "onDestroy" + this.getClass().toString());
super.onDestroy();
}
}
如此,每当Activity发生了对应的生命周期改变,Presenter就会执行对应事件注解的方法:除onCreate和onDestroy事件之外,Lifecycle一共提供了所有的生命周期事件,只要通过注解进行声明,就能够使LifecycleObserver观察到对应的生命周期事件。
2、源码分析
Lifecycle的使用很简单,接下来就是对Lifecycle原理和源码的解析了。
我们可以先猜下原理:LifecycleOwner(如Activity)在生命周期状态改变时(也就是生命周期方法执行时),遍历观察者,获取每个观察者的方法上的注解,如果注解是@OnLifecycleEvent且value是和生命周期状态一致,那么就执行这个方法。 这个猜测合理吧?下面你来看看。
2.1 Lifecycle类
先来瞅瞅Lifecycle:
public abstract class Lifecycle {
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
public abstract State getCurrentState();
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
Lifecycle 使用两种主要枚举跟踪其关联组件的生命周期状态:
- Event,生命周期事件,这些事件对应Activity/Fragment生命周期方法。
- State,生命周期状态,而Event是指进入一种状态的事件。
Event触发的时机:
- ON_CREATE、ON_START、ON_RESUME事件,是在LifecycleOwner对应的方法执行 之后 分发。
- ON_PAUSE、ON_STOP、ON_DESTROY事件,是在LifecycleOwner对应的方法调用 之前 分发。
这保证了LifecycleOwner是在这个状态内。
官网有个图很清晰:
2.2 Activity对LifecycleOwner的实现
前面提到Activity实现了LifecycleOwner,所以才能直接使用getLifecycle(),具体是在androidx.activity.ComponentActivity中:
public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner{
...
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
...
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
@CallSuper
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
Lifecycle lifecycle = getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).setCurrentState(Lifecycle.State.CREATED);
}
super.onSaveInstanceState(outState);
mSavedStateRegistryController.performSave(outState);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
这里忽略了一些其他代码,我们只看Lifecycle相关。
看到ComponentActivity实现了接口LifecycleOwner,并在getLifecycle()返回了LifecycleRegistry实例。前面提到LifecycleRegistry是Lifecycle具体实现。
然后在onSaveInstanceState()中设置mLifecycleRegistry的状态为State.CREATED,然后怎么没有了?其他生命周期方法内咋没处理?what?和猜测的不一样啊。
别急,在onCreate()中有这么一行:ReportFragment.injectIfNeededIn(this);,这个就是关键所在。
2.3 生命周期事件分发——ReportFragment
public class ReportFragment extends Fragment {
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
@SuppressWarnings("deprecation")
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
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);
}
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
...省略onStop、onDestroy
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
dispatch(getActivity(), event);
}
}
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
...
@Override
public void onActivityPostCreated(@NonNull Activity activity,@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_START);
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_RESUME);
}
@Override
public void onActivityPrePaused(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_PAUSE);
}
...省略onStop、onDestroy
}
}
首先injectIfNeededIn()内进行了版本区分:在API 29及以上 直接使用activity的registerActivityLifecycleCallbacks 直接注册了生命周期回调,然后给当前activity添加了ReportFragment,注意这个fragment是没有布局的。
然后, 无论LifecycleCallbacks、还是fragment的生命周期方法 最后都走到了 dispatch(Activity activity, Lifecycle.Event event)方法,其内部使用LifecycleRegistry的handleLifecycleEvent方法处理事件。
而ReportFragment的作用就是获取生命周期而已,因为fragment生命周期是依附Activity的。好处就是把这部分逻辑抽离出来,实现activity的无侵入。如果你对图片加载库Glide比较熟,就会知道它也是使用透明Fragment获取生命周期的。
2.4 生命周期事件处理——LifecycleRegistry
到这里,生命中周期事件的处理有转移到了 LifecycleRegistry 中:
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();
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;
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;
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 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);
}
逻辑很清晰:使用getStateAfter()获取event发生之后的将要处于的状态(看前面那张图很好理解),moveToState()是移动到新状态,最后使用sync()把生命周期状态同步给所有观察者。
注意到sync()中有个while循环,很显然是在遍历观察者。并且很显然观察者是存放在mObserverMap中的,而mObserverMap对观察者的添加 很显然 就是 Activity中使用getLifecycle().addObserver()这里:
@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) {
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();
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
sync();
}
mAddingObserverCounter--;
}
用observer创建带状态的观察者ObserverWithState,observer作为key、ObserverWithState作为value,存到mObserverMap。 接着做了安全判断,最后把新的观察者的状态 连续地 同步到最新状态mState,意思就是:虽然可能添加的晚,但会把之前的事件一个个分发给你,即粘性。 回到刚刚sync()的while循环,看看如何处理分发事件:
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;
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;
}
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 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();
}
}
}
循环条件是!isSynced(),若最老的和最新的观察者的状态一致,且都是ower的当前状态,说明已经同步完了。 没有同步完就进入循环体:
mState比最老观察者状态小,走backwardPass(lifecycleOwner):从新到老分发,循环使用downEvent()和observer.dispatchEvent(),连续分发事件; mState比最新观察者状态大,走forwardPass(lifecycleOwner):从老到新分发,循环使用upEvent()和observer.dispatchEvent(),连续分发事件。
接着ObserverWithState类型的observer就获取到了事件,即observer.dispatchEvent(lifecycleOwner, event),下面来看看它是如何让加了对应注解的方法执行的。
2.5 事件回调后 方法执行
我们继续看下 ObserverWithState:
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;
}
}
mState的作用是:新的事件触发后 遍历通知所有观察者时,判断是否已经通知这个观察者了,即防止重复通知。 mLifecycleObserver是使用Lifecycling.getCallback(observer)获取的GenericLifecycleObserver实例。GenericLifecycleObserver是接口,继承自LifecycleObserver:
public interface LifecycleEventObserver extends LifecycleObserver {
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
也就说,LifecycleEventObserver 给 LifecycleObserver 增加了感知生命周期状态变化的能力。 看看Lifecycling.getCallback(observer):
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
...省略很多类型判断的代码
return new ReflectiveGenericLifecycleObserver(object);
}
方法内有很多对observer进行类型判断的代码,我们这里关注的是ComponentActivity,所以LifecycleEventObserver的实现类就是ReflectiveGenericLifecycleObserver了:
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
它的onStateChanged()方法内部使用CallbackInfo的invokeCallbacks方法,这里应该就是执行观察者的方法了。
ClassesInfoCache内部用Map存了 所有观察者的回调信息,CallbackInfo是当前观察者的回调信息。
先看下CallbackInfo实例的创建,
ClassesInfoCache.sInstance.getInfo(mWrapped.getClass()):
private final Map<Class, CallbackInfo> mCallbackMap = new HashMap<>();
private final Map<Class, Boolean> mHasLifecycleMethods = new HashMap<>();
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<>();
...
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;
}
如果不存在当前观察者回调信息,就使用createInfo()方法收集创建 先反射获取观察者的方法,遍历方法 找到注解了OnLifecycleEvent的方法,先对方法的参数进行了校验。
第一个参数必须是LifecycleOwner;第二个参数必须是Event;有两个参数 注解值只能是ON_ANY;参数不能超过两个校验方法并加入到map,key是方法,value是Event。map handlerToEvent是所有的注解了生命周期的方法。
遍历完,然后用 handlerToEvent来构造 当前观察者回调信息CallbackInfo,存到ClassesInfoCache的mCallbackMap中,并记录 观察者是否有注解了生命周期的方法。
整体思路还是很清晰的,继续看CallbackInfo的invokeCallbacks方法:
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);
}
}
}
}
很好理解,执行对应event的方法、执行注解了ON_ANY的方法。其中mEventToHandlers是在创建CallbackInfo时由遍历mHandlerToEvent来获取,存放了每个Event对应的多个方法。 最后看看handlers.get(i).invokeCallback,即MethodReference中:
static class MethodReference {
...
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
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;
}
}
...
}
...
}
根据不同参数类型,执行对应方法。 到这里,整个流程就完整了。实际看了这么一大圈,基本思路和我们的猜想是一致的。
3、一些小Tips
3.1 尝试复用LifecycleRegistry
首先,LifecycleRegistry 本身就是一个成熟的 Lifecycle 实现类,它被实例化在Activity和Fragment中使用,如果我们需要自定义LifecycleOwner 并实现接口需要返回一个Lifecycle实例,完全可以直接在自定义LifecycleOwner中new一个LifecycleRegistry成员并返回它(简而言之就是:直接拿来用即可)。
以下是Google官方文档:
LifecycleRegistry: An implementation of Lifecycle that can handle multiple observers. It is used by Fragments and Support Library Activities. You can also directly use it if you have a custom LifecycleOwner.
3.2 注解和DefaultLifecycleObserver的取舍
其次,Google的Lifecycle库中提供了一个 DefaultLifecycleObserver 类,方便我们直接实现LifecycleObserver接口,相比较于文中demo所使用的注解方式,Google官方更推荐我们使用 DefaultLifecycleObserver 类,并声明
一旦Java 8成为Android的主流,注释将被弃用,所以介于DefaultLifecycleObserver和注解两者之间,更推荐使用 DefaultLifecycleObserver 。
官方原文:
3. 3 Lifecycles 的最佳实践
- 保持 UI 控制器(Activity 和 Fragment)尽可能的精简。它们不应该试图去获取它们所需的数据;相反,要用 ViewModel来获取,并且观察 LiveData将数据变化反映到视图中。
- 尝试编写数据驱动(data-driven)的 UI,即 UI 控制器的责任是在数据改变时更新视图或者将用户的操作通知给 ViewModel。
- 将数据逻辑放到 ViewModel 类中。ViewModel 应该作为 UI 控制器和应用程序其它部分的连接服务。注意:不是由 ViewModel 负责获取数据(例如:从网络获取)。相反,ViewModel 调用相应的组件获取数据,然后将数据获取结果提供给 UI 控制器。
- 使用Data Binding来保持视图和 UI 控制器之间的接口干净。这样可以让视图更具声明性,并且尽可能减少在 Activity 和 Fragment 中编写更新代码。如果你喜欢在 Java 中执行该操作,请使用像Butter Knife 这样的库来避免使用样板代码并进行更好的抽象化。
- 如果 UI 很复杂,可以考虑创建一个 Presenter 类来处理 UI 的修改。虽然通常这样做不是必要的,但可能会让 UI 更容易测试。
- 不要在 ViewModel 中引用View或者 Activity的 context。因为如果ViewModel存活的比 Activity 时间长(在配置更改的情况下),Activity 将会被泄漏并且无法被正确的回收。
|