Yoav Moran
Yoav Moran

Reputation: 107

Dagger 2 - two instances of the same View model are created

I’m trying to implement Dagger 2 in my Android app, and got stuck it this problem: The ActivityModels I use are created with an implementation of ViewModelProvider.Factory (as the example here). I attach the model to the activity by injecting the factory and calling:

viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyActivityViewModel.class);

In another part of the app I’m trying to use a Command class to make changes to the model, so I injected MyActivityViewModel directly to it.

@Inject
public SearchCommand(MyActivityViewModel viewModel) {
    super(viewModel);
}

The problem: The injected ViewModel is a new instance of the view model, different than the one instantiated in the Activity. Whatever I try I don’t manage to solve that… Any ideas?

Upvotes: 1

Views: 674

Answers (1)

marioavs
marioavs

Reputation: 121

I had the same issue, but following the code of ViewModelProviders, I changed just for the Fragment the first parameter of ViewModelProviders.of(this, viewModelFactory) by getActivity(). The resulting line is

viewModel = ViewModelProviders.of(getActivity(), viewModelFactory).get(MyActivityViewModel.class);

Upvotes: 3

Related Questions