简单介绍LiveData如何绑定在Activity和Fragment的生命周期,以及使用场景
一、类图
image二、总结
通过绑定Android系统组件或者自定义,管理生命周期
使用注解、反射实现模板方法,监听生命周期
使用观察者模式,监听数据变化
三、使用场景
定义MVP框架模式中的P的生命周期,就非常方便,不需要在基类BasePresenter中定义很多生命周期函数
public class Presenter<T extends Presenter.View> {
protected T view;
@CallSuper
public void onAttachView(T view) {
this.view = view;
}
@CallSuper
public void onDetachView() {
view = null;
}
public interface View {
}
}
public class ArcPresenter extends Presenter<ArcPresenterView> implements LifecycleObserver {
private static final String TAG = ArcPresenter.class.getSimpleName();
private final LifecycleOwner lifecycleOwner;
public ArcPresenter(LifecycleOwner lifecycleOwner) {
this.lifecycleOwner = lifecycleOwner;
}
private boolean isResume() {
return lifecycleOwner.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED);
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreate() {
Log.i(TAG, "onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void onStart() {
Log.i(TAG, "onStart");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume() {
Log.i(TAG, "onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void onPause() {
Log.i(TAG, "onPause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onStop() {
Log.i(TAG, "onStop");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy() {
Log.i(TAG, "onDestroy");
}
@Override
public void onAttachView(ArcPresenterView view) {
super.onAttachView(view);
Log.i(TAG, "onAttachView");
}
@Override
public void onDetachView() {
super.onDetachView();
Log.i(TAG, "onDetachView");
}
}
自定义有生命周期的组件
网友评论