Hi guys. I'm working on a trading app. I need to l...
# android-architecture
Hi guys. I'm working on a trading app. I need to list the user stocks and their value (profit or loss) among with the total value of the portfolio. For the holdings list, in an MVP architecture I would create a presenter for each list item but for this app I decided to use MVVM (Compose, ViewModels and Hilt ). My first idea was to create a different ViewModel for each list item. When using MVVM architecture, is what I'm trying to do the correct way or I should use a single ViewModel? Are you aware about any project I could have a look at? The image below is a super simplification of my actual screen, each cell complex and that's why I wanted to use a different ViewModel for each cell. Any suggestion is very welcome.
If the views are presenting different types of information, they should probably have different viewmodels, if they are presenting the same type of information just in a different way they should probably use the same viewmodel. The purpose of the viewmodel is essentially to provide the backing data presented in the UI as well as to bridge UI interactions to modify said data.
So, in the sample provided above, I’d probably use the same viewmodel for all of those items.
Hopefully understanding what the purpose of the viewmodel is will help you understand how you should implement it. Basically, narrow it down to what data is needed to be able to render the view, in this case, we need which holdings a user has, and the value of each of those holdings. So actually, in theory you could actually just use one viewmodel for this entire screen and it not be a violation of any design principles (at least I’m not aware of any violations in doing that), or, you can make use of recylerview similar and then each item would have its own copy of a viewmodel with the data it specifically needs (type of holding, and value) and that would also not be a violation of design principles and allow you to reuse the individual components (compose style)
👍 2