Reputation: 1396
I'm doing some codelabs of kotlin fundamentals and I don't really get in android with the ViewModel why sometimes there seems to be a need of creating it through a ViewModelFactory. Here you can see the codelab which talks about this.
They just say to perform the initialization using the factory method pattern but I don't understand the why. Why do we need to use factory pattern? Is it because we need to pass some parameter to the ViewModel? Or is it for some other reason? Is every time we need to create a ViewModelFactory just to pass parameters to the ViewModel?
I've been looking for the answer, trying to confirm whether is just to pass extra parameters or is because of any other reason but still I'm not sure and I haven't found the answer.
Upvotes: 2
Views: 598
Reputation: 3404
There are a few things that need to consider before using ViewModel
and ViewModelFactory
ViewModel
is LifecycleAware Components
.ViewModel
survive configuration
changes.ViewModelProvider' can only instantiate
ViewModel` with no-args contructor.Why do we need to use factory pattern?
To instantiate ViewModel
with arguments need to use ViewModelFactory
. ViewModelProviders
Utility can not create an instance of a ViewModel with argument constructor because it does not know how and what objects to pass in the constructor.
Also, you should follow the Dependency Injection principle. A class should not create dependencies it needs. It should be provided rather than creating.
For Example -
public class LogInViewModel extends ViewModel {
private final LogInRepo repo;
public LogInViewModel (LogInRepo repo) {
/* this.repo = new LogInRepo(); Not recommended, It violates DI principle*/
this.repo = repo;
}
}
Upvotes: 2