0

I have seen a number of references to ViewModel.Factory but every example I have come across has references to dependency injection. Based on this question: Why a viewmodel factory is needed in Android? it would seem that this is required when your constructor has parameters. Does this also apply to projects that aren't using dependency injection frameworks like Dagger?

Here is what I am trying to do:

public CatalogVerticalListViewModel(@NonNull Application application, RecyclerView.Adapter adapter) {
    super(application);

    final CatalogAdapter catalogAdapter = (CatalogAdapter) adapter;

    CatalogManager cm = new CatalogManager(Constants.BASE_URL);
    pageData = cm.getCatalog();
}

I need/want to pass my adapter into the ViewModel and I am wondering if I need to create a custom factory for this. If so, how would that look?

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
  • But why are you passing adapter to ViewModel? Shouldn't you use LiveData in ViewModel and Observe it in Activity/Fragment and then set the adapter? – Dhaval Jul 24 '19 at 18:41

1 Answers1

1

If you have a view model with constructor parameters you will have to write a factory for that. One way to avoid it is by removing those constructor paramters and setting these objects using methods (Not an adviced practice though).

Factory in your case will look like this,

public class CatalogViewModelFactory implements ViewModelProvider.Factory {
    private Application application;
    private RecyclerView.Adapter adapter;

    public CatalogViewModelFactory (@NonNull Application application, 
                  RecyclerView.Adapter adapter){
                this.application = application;
                this.adapter = adapter;

               }
        public <T extends ViewModel> T create(Class<T> modelClass) {
            if (modelClass.isAssignableFrom(CatalogVerticalListViewModel.class)) {
                return (T) new CatalogVerticalListViewModel(application,adapter);
            }
            throw new IllegalArgumentException("Unknown ViewModel class");
        }
    }

And use it in the activity,fragment... as

 CatalogViewModelFactory  factory =
            new CatalogViewModelFactory (application,adapter);

    viewModel = ViewModelProviders.of(this, factory).get(CatalogVerticalListViewModel.class);
Ramees Thattarath
  • 1,093
  • 11
  • 19