对ViewModel中的活动生命周期做出反应 [英] Reacting to activity lifecycle in ViewModel

查看:108
本文介绍了对ViewModel中的活动生命周期做出反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个使用MVVM架构的应用程序,有一件事我完全不了解.

I'm trying to create an app which will use MVVM architecture and there's one thing I quite don't understand.

Android官方文档说,在ViewModel的引用活动上下文不是一个好主意(因为ViewModel可能会超出活动),所以当我想在恢复活动时执行某些操作时,我就开始怀疑用例了.

Official Android docs say that's not a good idea to reference activity context in ViewModel's (as ViewModel may outlive activity) so I've started to wonder about usecase when I want to execute some action when my activity is resumed.

我知道ViewModel本身不应该执行业务逻辑,但是即使我使用某些服务类(假设GPSService必须启动并暂停每个活动,但必须在暂停时恢复活动),并且在此服务中,我会对onResume活动进行反应(使用生命周期观察者)我仍将通过ViewModel引用此活动,因为我正在引用服务,该服务持有对正在观察的活动的引用,这可能导致活动泄漏(如果我错了,请纠正我).

I know ViewModel's shouldn't do business logic themselves but even if I use some service class (let's say GPSService which has to start and pauseeach time activity is resumed on paused), and inside this service I react to activity onResume (using Lifecycle observer) I will still reference this activity from ViewModel as I'm referencing service which holds reference to activity being observed, this may cause activity leak (correct me if I'm wrong).

所以我的问题是,如何对MVVM体系结构中的活动或片段生命周期做出反应?

So my question is, how to react to activity or fragment lifecycle in MVVM architecture?

推荐答案

如果需要使ViewModel具有生命周期意识,则可以让它实现LifeCycleObserver并在必要时覆盖生命周期事件.例子,

If you need to have a ViewModel be lifecycle aware, then you can have it implement LifeCycleObserver and override life cycle events as necessary. Example,

public class MyModel extends ViewModel implements
    LifecycleObserver {

  @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  protected void onLifeCycleStop() {
      // do something
  }
}

在活动或片段中,您可以将视图模型添加到活动生命周期所有者中.

In the activity or fragment then you can add the view model to the activity life cycle owner.

public class MyActivity extends AppCompatActivity {

  protected MyModel mMyModel;

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      mMyModel = ViewModelProviders
          .of(this)
          .get(MyModel.class);

      getLifecycle().addObserver(mMyModel);
  }
}

这篇关于对ViewModel中的活动生命周期做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆