Android ViewModel recreated on screen rotation

前端 未结 4 1141
滥情空心
滥情空心 2021-02-14 11:01

I found a case when architecture components ViewModel isn\'t retained - in short it goes as follows:

  1. Activity is started and ViewModel in
4条回答
  •  眼角桃花
    2021-02-14 11:02

    AFAIK, ViewModel's only purpose is to survive and keep the data (i.e. "save the state") while its owner goes through different lifecycle events. So you don't have to "save the state" yourself.

    We can tell from this that it's "not normal behavior". onCleared() is only called after the activity is finished (and is not getting recreated again).

    Are you creating the ViewModel using the ViewModelProvider, or are you creating the instance using the constructor?

    In your activity, you should have something like:

    // in onCreate() - for example - of your activity
    model = ViewModelProviders.of(this).get(MyViewModel.class);
    // then use it anywhere in the activity like so
    model.someAsyncMethod().observe(this, arg -> {
        // do sth...
    });
    

    By doing this, you should get the expected effect.

提交回复
热议问题