I am implementing Room
database with ViewModel
. Everything works well. But the requirement is I want to provide some dependency to ViewModel
using AndroidViewModelFactory
. I am able to create ViewModelFactory
class which implements ViewModelProvider.Factory
. I am passing a normal String as a dependency to ViewModel. The code for Factory class is
public class TestViewModelFactory implements ViewModelProvider.Factory{
private static final String DEFAULT_LIMIT = "4";
static Application application;
static String created="ViewModelFactorySuccess";
public static TestViewModelFactory createFactory(Activity activity) {
application = activity.getApplication();
if (application == null) {
throw new IllegalStateException("Not yet attached to Application");
}
return new TestViewModelFactory(application, created);
}
public TestViewModelFactory(Application application, String created) {
application=application;
created=created;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
try {
return modelClass.getConstructor(TestViewModel.class, int.class)
.newInstance(application, created);
} catch (NoSuchMethodException | IllegalAccessException |
InstantiationException | InvocationTargetException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
}
}
}
In MainActivity
the normal instance of ViewModel
is created as
TestViewModel testViewModel=new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(TestViewModel.class);
which is working fine. But how to create a instance of ViewModel factory class so that a dependency can be provided to ViewModel.Please suggest the correct approach for ViewModel
instance creation. Any help would be appreciated.
Generic Example (up to android.arch.lifecycle:extensions:1.1.0). it is deprecated from 1.1.1,
MyViewModel myViewModel = new ViewModelProviders.of(this, new MyViewModelFactory(this.getApplication(), "Your string parameter")).get(MyViewModel.class);
Generic Example (for android.arch.lifecycle:extensions:1.1.1)
MyViewModel myViewModel = new ViewModelProvider(this, viewModelFactory).get(MyViewModel.class);
OR, Use ViewModelStore link
MyViewModel myViewModel = new ViewModelProvider(getViewModelStore(), viewModelFactory).get(MyViewModel.class);