https://kotlinlang.org logo
#compose
Title
# compose
r

robnik

12/16/2020, 11:19 PM
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

Sinan Gunes

12/17/2020, 2:27 AM
private
?
☝️ 1
r

robnik

12/17/2020, 2:07 PM
I tried removing
private
, but I get the same error.
s

Sinan Gunes

12/17/2020, 2:27 PM
@robnik what about
val model by viewModel<ContactSellerViewModel>()
?
r

robnik

12/17/2020, 2:30 PM
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() }
.
2 Views