From what I have read, it seems to be considered a best practice in MVVM for each View to have its own corresponding ViewModel, which makes sense, since the ViewModel is supposed to be the model of the View. Generally, reuse of ViewModels by different Views seems to be discouraged. Is this always the case? If not, what are the general guidelines for determining whether or not a ViewModel should be reused in this manner?
One situation I can think of where it might be satisfactory to reuse a ViewModel with a different View is when two Views make use of the exact same data from the Model and the Views themselves just represent the data differently. If the Views can handle representing the same data in different ways themselves, one ViewModel might be able to serve each View effectively.
The reason we have rules is so that you think before breaking them.
That is: there's nothing wrong with using the same ViewModel for two similar views. You do need to be very careful that your two views don't diverge, leaving you with a viewmodel that's attempting to do two different things.
This is why the recommendation is to have one viewmodel per view. Even though this might lead to duplication, it'll make maintaining the views easier in the long run.
As for the duplication, there's nothing wrong with viewmodel classes that have a shared base class.
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