1

I have the following code:

public class ProjectFragment extends LifecycleFragment implements Injectable {

@Inject
ViewModelProvider.Factory viewModelFactory;
private ProjectViewModel viewModel


@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

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

    // …
}

Source code from :https://proandroiddev.com/mvvm-architecture-viewmodel-and-livedata-part-2-di-1a6b1f96d84b

I would like to use directly the @Inject ProjectViewModel. How can I do that? I didn't find any example.

justmee
  • 355
  • 2
  • 14
  • Inject ViewModel directly impossible. You can do it only with factory. You can check this answer https://stackoverflow.com/a/44506312/9060113 and Google sample repository https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/ui/search/SearchFragment.kt – punchman Nov 13 '18 at 22:21
  • Thx @p.alexey. But why is impossible? Because there's no way to actually pass in a module provider the activity/ fragment context, right? – justmee Nov 13 '18 at 22:54
  • Thx for the link I did create a CustomFactoryModule and i do inject the viewModelFactory. – justmee Nov 13 '18 at 22:55
  • Because, for correct work you can't create ViewModel directly, only through the `ViewModelProviders` `ViewModelProviders.of(this).get(MyViewModel.class)`. And inject property through factory is a good approach. – punchman Nov 13 '18 at 23:24

0 Answers0