Ad

Why Repository Sends To Constructor Of ViewModel?

- 1 answer

I'm studying Google Architecture Components with MVVM and noticed that repository sends to constructor of ViewModel. The question is why repository can't exist as a property, field in ViewModel? Some developers create Factories where repository is stored and initialize ViewModel with it. What is the reason to do so? MVVM tells that View does not have to know about Model at all. So, why repository does not just stay at ViewModel as a field?

Ad

Answer

Typically the repository doesn't change over the lifetime of the ViewModel. Supplying it as a parameter of the contrustor instead of a property ensures that it can't be changed, and code in the ViewModel can rely on it.

If it was a property, it could be changed during the lifetime of the ViewModel. Your code could load an object from one database and find the repository pointing to a different database when it needed to save.

Ad
source: stackoverflow.com
Ad