Reacting to activity lifecycle in ViewModel

前端 未结 2 818
温柔的废话
温柔的废话 2021-02-12 15:15

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

Official Android docs say that\'s not a good idea to refe

2条回答
  •  孤独总比滥情好
    2021-02-12 15:50

    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);
      }
    }
    

提交回复
热议问题