我是新手,正在尝试将MVP与Lifecycle体系结构组件相结合。
众所周知,您应该在启动和停止时从PRESENTER附加和分离VIEW,以避免内存泄漏。但是,如果将View附加到Presenter上,则LifecycleOwner / LifecycleObserver无法正常工作。
出于学习目的,我创建了一个简单的(M)VP应用程序,该视图在onStart()和onStop()方法中附加到Presenter上和从其分离。很好。
之后,我将Presenter转换为LifecycleObserver,将其订阅LifecycleOwner事件(LifecycleOwner是View),然后从View中删除onStart()/ onStop()方法。在这种情况下,应用在启动时崩溃。
查看课程(v1):
public class MyView extends AppCompatActivity {
private final static String TAG = "myLogs";
MyPresenter myPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "CREATE");
setContentView(R.layout.activity_main);
myPresenter = new MyPresenter();
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "START");
myPresenter.linkView(this);
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "STOP");
myPresenter.unlinkView();
}
}
演示者类别(v1):
class MyPresenter {
private final static String TAG = "myLogs";
MyView view;
public void linkView(MyView v) {
Log.d(TAG, "linkView()");
this.view = v;
}
public void unlinkView() {
Log.d(TAG, "unlinkView()");
this.view = null;
}
}
这很好。
然后我尝试添加Lifecycle体系结构组件,如下所示:
查看课程(v2):
public class MyView extends AppCompatActivity {
private final static String TAG = "myLogs";
MyPresenter myPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "CREATE");
setContentView(R.layout.activity_main);
myPresenter = new MyPresenter();
getLifecycle().addObserver(myPresenter);
}
}
演示者类别(v2):
class MyPresenter implements LifecycleObserver {
private final static String TAG = "myLogs";
MyView view;
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void linkView(MyView v) {
Log.d(TAG, "linkView()");
this.view = v;
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void unlinkView() {
Log.d(TAG, "unlinkView()");
this.view = null;
}
}
区别是:
1. I add "implements LifecycleObserver" to MyPresenter;
2. add start/stop annotations to MyPresenter methods;
3. remove onStart()/onStop() methods from MyView;
4. subscribe MyPresenter to MyView lifecycle events in onCreate() method.
结果:
结果,应用在启动时崩溃,并出现以下错误异常:
无法启动活动MyView。必须是LifecycleOwner的一个实例
如果未将“查看”链接到“ Presenter”,则错误消失。但这打破了MVP模式。那么,Android上的MVP模式可以与Lifecycle结合吗?
答案 0 :(得分:1)
您需要检查您的 Lifecycle
是否至少处于 STARTED 状态,
作为解决方案,请考虑在 onStart()
调用之后将此代码放入您的super()
方法中:
getLifecycle().addObserver(myPresenter);
或者您可以通过检查条件将LifeCycle
对象传递给演示者,并将addObserver()
本身传递给演示者:
if (lifecycle.getCurrentState().isAtLeast(STARTED)) {
// Do your stuff here
}
来自here的更多内容,还请查看Lifecycle.States:
答案 1 :(得分:0)
您忘了覆盖
private final LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);
public LifecycleRegistry getLifecycle() {
return lifecycleRegistry;}
您至少需要Support-Lib 26.1