I have a project with 1 main activity and 4 fragments all inheriting from the same "BaseFragment".
When first started I managed the whole project with the same ViewModel all through the main activity and fragments but after a while, the code inside became too extensive and decided to split it in multiple ViewModels according to the necessities of each fragment/activity.
I created one "MainViewModel" and used it in the main activity and the rest of the ViewModels inherit from it.
My question is if it is a good practice for reducing the code in the ViewModel? is it perhaps inefficient to have multiple view models? what other ways are preferred to simplify it?
It is technically possible to have one ViewModel for all Fragment s.
The same ViewModel factory can be used for multiple ViewModels when they share dependencies, as it's the case for the Architecture Blueprints sample.
No that is fine; each object should be a ViewModel in its own right.
In fact you can have multiple view models for a single fragments doing different things for you. Keeping everything in one view model would make testing harder and also you have to keep viewmodel for all 20 fragments may be scoping to activity. Now I am considering to use a ViewModel but I am not sure whether it is worth the effor
Answer 2: I think if you are strict about your following of the pattern then each view has just one ViewModel. In In practical application, if the requirements change in the middle of the process, the easiest way is to have the view reference two different viewmodels. most welcome answer .
Usually, these types of mistakes happen when developers try to create objects of classes (e.g. a shared preference or network library that needs context in the ViewModel) instead of using a dependency mechanism like Dagger2 or Koin.
It’s the job of your site’s adapter to map the business model to your page’s ViewModel. Now, it might happen to be that your business model and view model are identical, but that’s coincidence, not design. The API should have no knowledge of what the web page needs to render, that’s the website’s responsibility.
Separation of concerns is almost never a bad thing. Ideally, each file/class should be responsible for one thing.
Additionally, you never know how the code will grow. Things tend to only get more complex over time, not usually simpler. So, while having multiple viewModels right now may feel like overkill, it will likely pay off later.
One case where a shared viewmodel between several fragments is ideal is when the fragments need to communicate with each other - they all would then use the activity viewmodel.
I would assume in this case you can use both approaches, though I have never done it, so I can't say for certain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With