Search code examples
androidandroid-viewmodelandroid-mvvm

save instance state in AndroidViewModel


I'm learning to use MVVM for my application, because of this I have to extend my viewmodel using AndroidViewModel instead of ViewModel, so that I can have the application contextfor the repository stuff, but this is not the problem.

The problem is that I used to have savedStateHandle as parameter in the constructor the viewmodel that extends ViewModel as below:

public class MainViewModel extends ViewModel {

    private static String SAVED_KEY_STARTED = "started";
    private MutableLiveData<Boolean> isStarted;
    SavedStateHandle savedState;

    public MainViewModel(SavedStateHandle savedStateHandle){
        savedState = savedStateHandle;

        isStarted = new MutableLiveData(Boolean.False);

        if(savedStateHandle.contains(SAVED_KEY_STARTED)){
                isStarted.setValue(savedStateHandle.get(SAVED_KEY_STARTED));
        }
    }

    // some other getters setters that set values into `savedState` on the fly
    ...
}

Now, using viewmodel that extends AndroidViewModel, the contructor no longer has this, instead it only pass in a application context. How can I save and retrieve instance state using AndroidViewModel.

public class MainViewModel extends AndroidViewModel {
    public MainViewModel(Application application){
    }
}

Added:
code to retrieve viewmodel

// im using this for a fragment within my main activity 
viewModel =
        new ViewModelProvider(requireActivity(),
                ViewModelProvider
                        .AndroidViewModelFactory
                        .getInstance(requireActivity().getApplication())
        ).get(MainViewModel.class);

Solution

  • viewModel =
            new ViewModelProvider(requireActivity()).get(MainViewModel.class);
    
    public class MainViewModel extends AndroidViewModel {
        public MainViewModel(Application application, SavedStateHandle savedStateHandle){
            super(Application application);
        }
    }