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
You can use a ViewModelFactory
:
val viewModelFactory = VMFactory(requireActivity().application)
viewModel= ViewModelProvider(requireActivity(),viewModelFactory).get(MainViewModel::class.java)
VMFactory code:
class VMFactory(application: Application) : ViewModelProvider.NewInstanceFactory() {
val _application: Application=application
@NonNull
override fun create(@NonNull modelClass: Class): T {
return MainViewModel(_application) as T
}
}
Please note that here my MainViewModel
extends AndroidViewModel
and hence requires application as the input parameter.