Annotation Interface HiltViewModel


@Target(TYPE) @Retention(CLASS) public @interface HiltViewModel
Identifies a ViewModel for construction injection.

The ViewModel annotated with HiltViewModel will be available for creation by the

invalid @link
dagger.hilt.android.lifecycle.HiltViewModelFactory
and can be retrieved by default in an Activity or Fragment annotated with AndroidEntryPoint. The HiltViewModel containing a constructor annotated with Inject will have its dependencies defined in the constructor parameters injected by Dagger's Hilt.

Example:

 @HiltViewModel
 public class DonutViewModel extends ViewModel {
     @Inject
     public DonutViewModel(SavedStateHandle handle, RecipeRepository repository) {
         // ...
     }
 }
 
 @AndroidEntryPoint
 public class CookingActivity extends AppCompatActivity {
     public void onCreate(Bundle savedInstanceState) {
         DonutViewModel vm = new ViewModelProvider(this).get(DonutViewModel.class);
     }
 }
 

ViewModels annotated with HiltViewModel can also be used with assisted injection:

 @HiltViewModel(assistedFactory = DonutViewModel.Factory.class)
 public class DonutViewModel extends ViewModel {
     @AssistedInject
     public DonutViewModel(
         SavedStateHandle handle,
         RecipeRepository repository, 
         $#64;Assisted int donutId
     ) {
         // ...
     }

     @AssistedFactory
     public interface Factory {
         DonutViewModel create(int donutId);
     }
 }
 
 @AndroidEntryPoint
 public class CookingActivity extends AppCompatActivity {
     public void onCreate(Bundle savedInstanceState) {
         DonutViewModel vm = new ViewModelProvider(
             getViewModelStore(),
             getDefaultViewModelProviderFactory(),
             HiltViewModelExtensions.withCreationCallback(
                 getDefaultViewModelCreationExtras(),
                 (DonutViewModel.Factory factory) -> factory.create(1)
             )
         ).get(DonutViewModel.class);
     }
 }
 

Exactly one constructor in the ViewModel must be annotated with Inject or AssistedInject.

Only dependencies available in the ViewModelComponent can be injected into the ViewModel.

See Also:
  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
    Returns a factory class that can be used to create this ViewModel with assisted injection.
  • Element Details

    • assistedFactory

      Class<?> assistedFactory
      Returns a factory class that can be used to create this ViewModel with assisted injection. The default value `Object.class` denotes that no factory is specified and the ViewModel is not assisted injected.
      Default:
      java.lang.Object.class