I am building an app like Gmail with compose. In portrait mode, it only shows the list messages as the main screen of the app, and when the user clicks on one message, the app will navigate to message detail screen. Both screens have a ViewModel: MessagesListViewModel and MessageDetailViewModel.
In landscape mode, I want to show both screens at once, next to each other: on the left side, messages list screen and on the right side, message detail screen of the selected message.
My solution to do that, is that I create a route for message list screen to handle different cases:
- If the app is in portrait mode and no message is selected, it will only show the message list screen
- If the app is in portrait mode and a message is selected, instead of show message list screen, the app with show the message detail screen
- If the app is in landscape mode, it will show both screen.
So basically I have a compose function that handles all this cases. My question here, is it a good practice to have multiple view models in this compose function?
CodePudding user response:
There's unlikely to be one right answer here, but per
as per @fstanis answer, is it like that, there is no right answer, it depends on what architecture you want to follow and how you want to do it.
From what you describe you can do it both ways
Having 1 ViewModel
for everything (take care that it could have more code than separating these into different ViewModels
)
Benefits
- You contain all these 3 screens into 1
ViewModel
- No more instances for any new viewmodel
- You can share data/communicate between these 3 screens with this one
ViewModel
Cons
- It could bloat your
ViewModel
with a lot of code (depending on your case)
The other way is to have 1 ViewModel
per composable, that can separate the logic, but it depends if you need to communicate data between them, if you need to communicate, you will need to send arguments between the navigation of each screen and live the ViewModels
in the respective composable