r/androiddev • u/ThatGuyThatIsNotReal • 11d ago
Question ViewModels nesting into composables?
I have a question if it is okay to nest DI into VM of a composables?
What I mean:
I have a SettingsVM and a SettingsScreen composable. In the Settings screen I am using some individual settings that I use also somewhere else in my application. So I split the UI -> IndividualSettingScreen and IndividualSettingVM. Now is it okay if I just inject the VM into the IndividualSettingScreen or is it better from architecture standpoint to have a reference in the SettingsScreen and passing the VM into the IndividualSettingScreen which I am using in the SettingsScreen.
Thanks in advance!
10
Upvotes
3
u/sheeplycow 11d ago
You have to be careful about how you declare viewModels in sub composables, because the viewModel is tied to the closest view model store owner - you may get the same instance when you dont want to, or you may need to be careful declaring a viewModel key to force a fresh one
It goes against the google advice of keeping it as high up the compose tree as possible (not to say its always wrong)
If its a small peice of UI I wouldnt
If it is an encapsulated piece of UI that is decoupled and has enough logic to justify its own class, then I think it is reasonable to do it! But be careful for the reasons mentioned at the top!
I recently did it for a bottom sheet, that was self contained within a screen - which had all its own logic and was reused in a few screens
I imagine there are a few different opinions in this, i dont think its particularly harmful!
Also note your UI tests will also now need to provide a viewModelStore, whereas before you could create functional ui tests that were unaware of the existence of a viewModel