https://kotlinlang.org logo
c

Corey Lanier

11/20/2020, 2:29 AM
Hi all, I’m studying MVVM, and having a hard time grasping why a ViewModelFactory would go with a ViewModel when it is sent to a fragment. I’ve seen the ViewModel work standalone as well, so I’m just wondering what benefit using a ViewModelFactory provides. And yes, I’ve been to SO and Google, and yet I still don’t fully grasp the concept, so shoot me.
google 4
stackoverflow 4
j

Joost Klitsie

11/20/2020, 7:56 AM
I do not know what you specifically mean with "when it is sent to a fragment", but you need the factory to create a viewmodel, when it has dependencies (aka constructor arguments) so if you have a viewmodel:
Copy code
class MyViewModel(val myRepository: MyRepository): ViewModel()
Then when you are creating this
MyViewModel
, the
myRepository
must be given somehow. A factory will be able to do that.
This is because you do not instantiate the viewmodel yourself with the architecture components, but you try to get an existing one from the current viewmodelstore. So for example, if you want to have your viewmodel be on an Activity level, you use the activity as viewModelStoreOwner, if you want to use it on a fragment you use the fragment as a viewModelStoreOwner, but you can even link it to navigation graphs from the Navigation component. Therefore, there is no clear place to say: This is when the viewModel will be created! So instead of creating the viewmodel, you give a factory that can create the viewmodel when it is deemed necessary.
if you have a no-arg constructor, a factory is not needed as we do not have to put in the dependencies. But usually you will have arguments.
The factory is basically wrapping around all the dependencies the viewmodel would need and can create a fresh new viewmodel when necessary.
👍 2