I am new to the mvvm pattern. I created a ViewModel for the main activity. Now I want to get an instance of the ViewModel in the main activity.
Most Tutorials and answe
For now, the only thing working for me was to use:
MainActivityViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MainActivityViewModel.class);
However, I am still thankful for any advice, how this can be done different using new ViewModelProvider(this).get(MainActivityViewModel.class);
You should update your gradle file to:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
And due to this change you can pass Activity to the constructor you mentioned:
mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
Using Fragment-ktx libr in your app you can get viewModel as below
implementation 'androidx.fragment:fragment-ktx:1.1.0'
// get ViewModel in Activity or Fragment as
private val viewModel: MainActivityViewModel by viewModels()
// If you want to get same instance of ViewModel in ChildFragment as
private val viewModel: MainActivityViewModel by viewModels(
ownerProducer = { requireParentFragment() }
)