When I try to create a ViewModel in a Composable I...
# compose
r
When I try to create a ViewModel in a Composable I get this error: "java.lang.ClassCastException: java.lang.Object cannot be cast to androidx.lifecycle.ViewModel" The line is as show in the docs:
val model: ContactSellerViewModel by viewModel()
Any ideas?
And yes, the class inherits from ViewModel...
private class ContactSellerViewModel: ViewModel() { ...
s
private
?
☝️ 1
r
I tried removing
private
, but I get the same error.
s
@robnik what about
val model by viewModel<ContactSellerViewModel>()
?
r
That gives me an error about a missing getValue function and doesn't provide an import suggestion. I wonder also if I have a Gradle problem: when I click on the stack trace it shows two jars. (Screenshot attached)
Well I got rid of the double jars by listing some explicit deps in my build.gradle file. I can debug step into the viewModel(...) function and see that it's not getting its reified type parameter correctly. The call looks like
viewModel(VM::class.java, key, factory)
but that first param just
Object
, not my class. I guess I will manually create my models for now, like:
val model = remember { MyViewModel() }
.