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

Tin Tran

08/31/2021, 8:54 AM
Hi! How do I create different instances of a ViewModel on the same destination?
Copy code
composable(route = "a") {
    Component1(hiltViewModel())
    Component1(hiltViewModel())
}
a

adjpd

08/31/2021, 1:14 PM
When you do you want to use a different view model instance?
t

Tin Tran

08/31/2021, 1:21 PM
I have a composable that have multiple sub component. Each of them is a composable. How the component is arranged is read from a server. Each component have multiple state so I give each component a view model. It work fine when you have the same component only once. But if I add a component 2 times , both of the view models are the same instance and the later added component affects the component added before it.
Hope I clear things out a bit
a

adjpd

08/31/2021, 3:20 PM
I think you're using hilt which I have little experience with. But ViewModels are one instance. That's there whole point. I think you're trying to use a viewmodel, which is a singleton, twice and expecting them not to be a singleton.
t

Tin Tran

08/31/2021, 4:39 PM
Thanks. I’m using it the wrong way I guess.
j

JulianK

09/01/2021, 6:30 AM
I have a similar situation where i need multiple instances for multiple tabs. I'm not using Android Architecture Components ViewModels in this case, but instead just Pojos. To get them injected via Hilt, use EntryPoints https://developer.android.com/training/dependency-injection/hilt-android#not-supported The default Hilt ViewModels are always Singletons.
2 Views