Manually clearing an Android ViewModel?

后端 未结 12 1048
独厮守ぢ
独厮守ぢ 2020-12-04 18:50

Edit: This question is a bit out of date now that Google has given us the ability to scope ViewModel to navigation graphs. The better approach (rather

12条回答
  •  春和景丽
    2020-12-04 19:29

    I found a simple and fairly elegant way to deal with this issue. The trick is to use a DummyViewModel and model key.

    The code works because AndroidX checks the class type of the model on get(). If it doesn't match it creates a new ViewModel using the current ViewModelProvider.Factory.

    public class MyActivity extends AppCompatActivity {
        private static final String KEY_MY_MODEL = "model";
    
        void clearMyViewModel() {
            new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).
                .get(KEY_MY_MODEL, DummyViewModel.class);
        }
    
        MyViewModel getMyViewModel() {
            return new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication()).
                .get(KEY_MY_MODEL, MyViewModel.class);
        }
    
        static class DummyViewModel extends ViewModel {
            //Intentionally blank
        }
    }   
    

提交回复
热议问题