When I try to initialize viewmodel in an Activity which extends ComponentActivity, I can use “by viewModels(..)” . However if I try to instantiate the same in an activity that extents AppCompactActivity, it remains unresolved.
I checked the source code of ‘by viewModel’, looks like its only applicable on ComponentActivity,
public inline fun <reified VM : ViewModel> ComponentActivity.viewModels(
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
val factoryPromise = factoryProducer ?: {
defaultViewModelProviderFactory
}
return ViewModelLazy(
VM::class,
{ viewModelStore },
factoryPromise,
{ extrasProducer?.invoke() ?: this.defaultViewModelCreationExtras }
)
}
Is there a way in which I can also use this function under AppCompactActivity?
I have tried adding the following dependencies:
implementation("androidx.activity:activity-ktx:1.9.0")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.3")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.3")
implementation("androidx.fragment:fragment-ktx:1.8.1")
implementation("androidx.core:core-ktx:1.13.1")
implementation("androidx.navigation:navigation-fragment-ktx:2.7.7")
implementation("androidx.navigation:navigation-ui-ktx:2.7.7")
implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.8.3")
Abhishek Maharajpet is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
9