1

I am learning Dagger2 with MVVM Architecture. I have one question I was reading some documents and watching videos.

I knew we can reduce lots of boilerplate code for some of the out stuff like singleton pattern and some other stuff that we are going to use throughout the application.

I was developing one app for the learning purpose and I am using MVVM and Dagger2. My question is: for injecting view model providers we need to write too many boilerplate codes to inject the view model providers and it will be only available to that activity life cycle. We can achieve this by just simple code. Why should we use Dagger2 what is the actual use? I searched for it and didn't find anything useful.

Here is my code with dagger2:

@Inject
ViewModelProviderFactory providerFactory;

viewModel = ViewModelProviders.of(this,providerFactory).get(AuthViewModel.class);

To inject ViewModelProviderFactory I need to write some boilerplate codes.

Here is my code without dagger2:

 mMainActivityViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);

Both served the purpose but I am not getting what is the best and why?

Harsh Shah
  • 2,162
  • 2
  • 19
  • 39

1 Answers1

0

You show not single option to initialize view model. Every way has advantages and disadvantages. When you want to introduce viewmodel with inject constructor in an activity or a fragment we have two problems, firstly, during usual implementation, the model will be recreated every time the screen is rotated, and secondly, by default, ViewModelProviders does not support any constructors with parameters.

So you need to create your own model provider, and implement it in activity.

Andrey Molochko
  • 727
  • 1
  • 6
  • 21