Does anyone know what is the proper way to use Fac...
# compose
j
Does anyone know what is the proper way to use Factory with viewModel() functions? I couldn't find any official example (the best I could find was this Stack post, but I'm not sure using an object is ideal) https://stackoverflow.com/questions/67985585/why-do-we-need-viewmodelprovider-factory-to-pass-view-model-to-a-screen
c
It is up to you how you will pass down the factory to the screens. You can have a singleton object, create a
CompositionLocal
to hold the factory, or pass the factory as a parameter to every screen. Depends on your architecture.
j
@Csaba Kozák It's not clear to me how you can pass the factory to the screens when using viewModel() functions, would you happen to have an example at hand?
c
Copy code
@Composable
fun HomeScreen(factory: ViewModelProvider.Factory) {
  val homeViewModel: HomeViewModel = viewModel(factory = factory)
}
Of course you have to create the factory somewhere upwards.
j
Awesome, thanks @Csaba Kozák!