I am practicing Google MVVM https://github.com/googlesamples/android-architecture/tree/todo-mvvm-databinding, having a problem of linking Fragment and ViewModel.
The google demo doing like this:
in Activity,
Fragment.newInstance()new ViewModel()fragment.setViewModel(viewModel). (Implementing a setViewModel method in Fragment)viewmodel.loadingData() in fragment's onResume or onStart
My question is, this seems not safe. If due to some reason, system recycle fragment and recreate using default constructor, viewModel will be null ?
am I right or am I missing something?
As a workaround, I think put the new ViewModel() in Fragment's onCreateView method should be fine?
You should not create new instance of the ViewModel anywhere in
FragmentorActivity. The correct way is to obtain the instance by using theViewModelProvidersand aViewModelProvider.FactoryThere are many article around the net about
MVVMandViewModelusingdagger2such as this or this