When using Jetpack Compose navigation, would one use one ViewModel for all screens or one ViewModel for each screen? Is there any architecture guidance on this? And if one would use multiple ViewModels, where would one instantiate them?
I'm no professional when it comes to architectural design in software but I think that it all depends on your app's structure. Compose is basically a UI framework, and it's not a replacement for ViewModels. This means that you still have all the flexibility to go about it any way you see fit.
For example, if you have multiple different screens (i.e. Login, Home, Settings, etc.), you're probably better off using a separate ViewModel for each screen. If you have a very simple one-pager, you could get away with a single ViewModel.
The official docs have a pretty good description on how to go about structuring your app. You should obviously make any necessary adjustments in order to make the architecture fit your projects needs & goals.
As for the instantiation part, you can either follow the suggested (no D.I.) way, i.e.:
class ExampleViewModel : ViewModel() { /*...*/ }
@Composable
fun MyExample(
viewModel: ExampleViewModel = viewModel()
) {
// use viewModel here
}
or you could (and probably should) use a D.I. library such as Hilt or Koin.
© 2022 - 2024 — McMap. All rights reserved.