Reputation: 8371
I was wondering why the ViewModel with different parameters in the constructor needs a ViewModel Provider Factory . Why can't a ViewModel be instantiated with a regular constructor new MyViewModel(parameter1 , parameter2);
Upvotes: 1
Views: 192
Reputation: 11032
Nothing is stopping you from creating ViewModel
objects with a new
keyword. Essentially when there are no constructor parameters provided, that is what Factory Provider does internally, But there are other functionalities wrapped around it. For example lifecycle management. ViewModel in specifically tied to lifecycle constructs such as Fragments and Activities. When things get complicated enough, you would need objects factories for the dependency management.
For the simple example you have given
val vm = MyViewModel(height=10, weight=20)
It's easier to create those height and weight objects since they are integers but what if it's a complex dependency such as
val vm = MyViewModel(repo=MyRepository())
And what if MyRepository
in turns may have dependencies on Retrofit, Room DataBase, Shared Preference.. etc
Now that's where Factory patterns comes into play. Factory patterns can be easily be auto generated using Dependency Injection tools such as Dagger.
Factory patterns are for sophisticated dependency providing mechanism.
Upvotes: 1