• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Dagger Authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package dagger.hilt.android.lifecycle;
18 
19 import dagger.hilt.GeneratesRootInput;
20 import java.lang.annotation.ElementType;
21 import java.lang.annotation.Retention;
22 import java.lang.annotation.RetentionPolicy;
23 import java.lang.annotation.Target;
24 
25 /**
26  * Identifies a {@link androidx.lifecycle.ViewModel} for construction injection.
27  *
28  * <p>The {@code ViewModel} annotated with {@link HiltViewModel} will be available for creation by
29  * the {@link dagger.hilt.android.lifecycle.HiltViewModelFactory} and can be retrieved by default in
30  * an {@code Activity} or {@code Fragment} annotated with {@link
31  * dagger.hilt.android.AndroidEntryPoint}. The {@code HiltViewModel} containing a constructor
32  * annotated with {@link javax.inject.Inject} will have its dependencies defined in the constructor
33  * parameters injected by Dagger's Hilt.
34  *
35  * <p>Example:
36  *
37  * <pre>
38  * &#64;HiltViewModel
39  * public class DonutViewModel extends ViewModel {
40  *     &#64;Inject
41  *     public DonutViewModel(SavedStateHandle handle, RecipeRepository repository) {
42  *         // ...
43  *     }
44  * }
45  * </pre>
46  *
47  * <pre>
48  * &#64;AndroidEntryPoint
49  * public class CookingActivity extends AppCompatActivity {
50  *     public void onCreate(Bundle savedInstanceState) {
51  *         DonutViewModel vm = new ViewModelProvider(this).get(DonutViewModel.class);
52  *     }
53  * }
54  * </pre>
55  *
56  * <p>Exactly one constructor in the {@code ViewModel} must be annotated with {@code Inject}.
57  *
58  * <p>Only dependencies available in the {@link dagger.hilt.android.components.ViewModelComponent}
59  * can be injected into the {@code ViewModel}.
60  *
61  * <p>
62  *
63  * @see dagger.hilt.android.components.ViewModelComponent
64  */
65 @Target(ElementType.TYPE)
66 @Retention(RetentionPolicy.CLASS)
67 @GeneratesRootInput
68 public @interface HiltViewModel {}
69