title: How to Implement ViewModel Factory in Android
body: <p>I am implementing <code>Room</code> database with <code>ViewModel</code>. Everything works well.  But the requirement is I want to provide some dependency to <code>ViewModel</code> using <code>AndroidViewModelFactory</code>. I am able to create <code>ViewModelFactory</code> class which implements <code>ViewModelProvider.Factory</code>. I am passing a normal String as a dependency to ViewModel. The code for Factory class is  </p>
  
  <pre><code>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 &lt;T extends ViewModel&gt; T create(@NonNull Class&lt;T&gt; 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);
          }
      }
  }  
  </code></pre>
  
  <p>In <code>MainActivity</code> the normal instance of <code>ViewModel</code> is created as </p>
  
  <pre><code>TestViewModel testViewModel=new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(TestViewModel.class);  
  </code></pre>
  
  <p>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 <code>ViewModel</code> instance creation. Any help would be appreciated.</p>