How To Instantiate Viewmodel That Extends Androidviewmodel?
I'm following a tutorial where a ViewModel extends an abstract class in order to use coroutines, this is the class that extends: abstract class BaseViewModel(application: Applicati
Solution 1:
Your ViewModel
is child of AndroidViewModel
which require an Application
object. So you will have to provide the Factory
class in order to instantiate the ViewModel
. Like so:
val viewModelProvider = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory(application)
)
viewModel = viewModelProvider[MainViewModel::class.java]
If you are using the fragment library from Jetpack
implementation "androidx.fragment:fragment-ktx:1.2.5"
You can use property delegation like so:
val viewModel: ViewModel by viewModels()
Post a Comment for "How To Instantiate Viewmodel That Extends Androidviewmodel?"