모든 Hilt ViewModel은 ViewModel과 동일한 수명 주기를 따르는 ViewModelComponent에서 제공되며, 따라서 구성 변경 후에도 유지될 수 있습니다.
종속 항목의 범위를 ViewModel로 지정하려면 @ViewModelScoped 주석을 사용하세요.
@ViewModelScoped 유형을 사용하면 ViewModel에 삽입된 모든 종속 항목에 걸쳐 범위가 지정된 유형의 단일 인스턴스가 제공됩니다.
범위가 지정된 인스턴스를 요청하는 ViewModel의 다른 인스턴스는 다른 인스턴스를 수신합니다.
단일 인스턴스를 다양한 ViewModel에서 공유해야 하는 경우 @ActivityRetainedScoped 또는 @Singleton을 사용하여 범위를 지정해야 합니다.
Gradle 파일에 다음과 같은 종속 항목을 추가합니다. 라이브러리 외에도 Hilt 주석 프로세서를 기반으로 작동하는 추가 주석 프로세서를 포함해야 합니다.
app/build.gradle
Groovy
dependencies{...implementation'androidx.hilt:hilt-work:1.0.0'// When using Kotlin.kapt'androidx.hilt:hilt-compiler:1.0.0'// When using Java.annotationProcessor'androidx.hilt:hilt-compiler:1.0.0'}
Kotlin
dependencies{implementation("androidx.hilt:hilt-work:1.0.0")// When using Kotlin.kapt("androidx.hilt:hilt-compiler:1.0.0")// When using Java.annotationProcessor("androidx.hilt:hilt-compiler:1.0.0")}
클래스의 @HiltWorker 주석과 Worker 객체의 생성자의 @AssistedInject를 사용하여 Worker를 삽입합니다. Worker 객체에는 @Singleton 또는 범위가 지정되지 않은 결합만 사용할 수 있습니다. 또한 다음과 같이 Context 및 WorkerParameters 종속 항목에 @Assisted로 주석을 지정해야 합니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-27(UTC)"],[],[],null,["# Use Hilt with other Jetpack libraries\n\nHilt includes extensions for providing classes from other Jetpack libraries.\nHilt currently supports the following Jetpack components:\n\n- `ViewModel`\n- Navigation\n- Compose\n- WorkManager\n\nYou must add the Hilt dependencies to take advantage of these integrations. For\nmore information about adding dependencies, see [Dependency injection with\nHilt](/training/dependency-injection/hilt-android#setup).\n\nInject ViewModel objects with Hilt\n----------------------------------\n\nProvide a [`ViewModel`](/topic/libraries/architecture/viewmodel) by annotating\nit with `@HiltViewModel` and using the `@Inject` annotation in the `ViewModel`\nobject's constructor. \n\n### Kotlin\n\n```kotlin\n@HiltViewModel\nclass ExampleViewModel @Inject constructor(\n private val savedStateHandle: SavedStateHandle,\n private val repository: ExampleRepository\n) : ViewModel() {\n ...\n}\n```\n\n### Java\n\n```java\n@HiltViewModel\npublic class ExampleViewModel extends ViewModel {\n\n private final ExampleRepository repository;\n private final SavedStateHandle savedStateHandle;\n\n @Inject\n ExampleViewModel(\n SavedStateHandle savedStateHandle,\n ExampleRepository repository)\n {\n this.savedStateHandle = savedStateHandle;\n this.repository = repository;\n }\n ...\n}\n```\n\nThen, an activity or a fragment that is annotated with `@AndroidEntryPoint` can\nget the `ViewModel` instance as normal using `ViewModelProvider` or the\n`by viewModels()` [KTX extensions](/kotlin/ktx): \n\n### Kotlin\n\n```kotlin\n@AndroidEntryPoint\nclass ExampleActivity : AppCompatActivity() {\n private val exampleViewModel: ExampleViewModel by viewModels()\n ...\n}\n```\n\n### Java\n\n```java\n@AndroidEntryPoint\npublic class ExampleActivity extends AppCompatActivity {\n\n private ExampleViewModel exampleViewModel;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n exampleViewModel = new ViewModelProvider(this).get(ExampleViewModel.class);\n }\n ...\n}\n```\n| **Note:** To use Dagger's assisted injection with ViewModels, see the following [Github issue](https://github.com/google/dagger/issues/2287).\n\n### @ViewModelScoped\n\nAll Hilt ViewModels are provided by the `ViewModelComponent` which follows the\nsame lifecycle as a `ViewModel`, and as such, can survive configuration changes.\nTo scope a dependency to a `ViewModel` use the `@ViewModelScoped` annotation.\n\nA `@ViewModelScoped` type will make it so that a single instance of the scoped\ntype is provided across all dependencies injected into the `ViewModel`.\nOther instances of a ViewModel that request the scoped instance will receive\na different instance.\n\nIf a single instance needs to be shared across various ViewModels, then it\nshould be scoped using either `@ActivityRetainedScoped` or `@Singleton`.\n\nIntegration with the Jetpack navigation library\n-----------------------------------------------\n\nAdd the following additional dependencies to your Gradle file:\n\napp/build.gradle \n\n### Groovy\n\n```groovy\ndependencies {\n ...\n implementation 'androidx.hilt:hilt-navigation-fragment:1.0.0'\n}\n```\n\n### Kotlin\n\n```kotlin\ndependencies {\n ...\n implementation(\"androidx.hilt:hilt-navigation-fragment:1.0.0\")\n}\n```\n\nIf your `ViewModel` is [scoped to the navigation\ngraph](/guide/navigation/navigation-programmatic#share_ui-related_data_between_destinations_with_viewmodel),\nuse the `hiltNavGraphViewModels` function that works with fragments that are\nannotated with `@AndroidEntryPoint`. \n\n### Kotlin\n\n```kotlin\nval viewModel: ExampleViewModel by hiltNavGraphViewModels(R.id.my_graph)\n```\n\n### Java\n\n```java\nNavBackStackEntry backStackEntry = navController.getBackStackEntry(R.id.my_graph);\n\nExampleViewModel exampleViewModel = new ViewModelProvider(\n backStackEntry,\n HiltViewModelFactory.create(context, backStackEntry)\n).get(ExampleViewModel.class)\n```\n\nIntegration with Jetpack Compose\n--------------------------------\n\nTo see how Hilt integrates with Jetpack Compose, see the Hilt section of\n[Compose and other libraries](/jetpack/compose/libraries#hilt).\n\nInject WorkManager with Hilt\n----------------------------\n\nAdd the following additional dependencies to your Gradle file. Note that in\naddition to the library, you need to include an additional annotation processor\nthat works on top of the Hilt annotation processor:\n\napp/build.gradle \n\n### Groovy\n\n```groovy\ndependencies {\n ...\n implementation 'androidx.hilt:hilt-work:1.0.0'\n // When using Kotlin.\n kapt 'androidx.hilt:hilt-compiler:1.0.0'\n // When using Java.\n annotationProcessor 'androidx.hilt:hilt-compiler:1.0.0'\n}\n```\n\n### Kotlin\n\n```kotlin\ndependencies {\n implementation(\"androidx.hilt:hilt-work:1.0.0\")\n // When using Kotlin.\n kapt(\"androidx.hilt:hilt-compiler:1.0.0\")\n // When using Java.\n annotationProcessor(\"androidx.hilt:hilt-compiler:1.0.0\")\n}\n```\n\nInject a [`Worker`](/reference/kotlin/androidx/work/Worker) using the\n`@HiltWorker` annotation in the class and `@AssistedInject` in the `Worker`\nobject's constructor. You can use only `@Singleton` or unscoped bindings in\n`Worker` objects. You must also annotate the `Context` and `WorkerParameters`\ndependencies with `@Assisted`: \n\n### Kotlin\n\n```kotlin\n@HiltWorker\nclass ExampleWorker @AssistedInject constructor(\n @Assisted appContext: Context,\n @Assisted workerParams: WorkerParameters,\n workerDependency: WorkerDependency\n) : Worker(appContext, workerParams) { ... }\n```\n\n### Java\n\n```java\n@HiltWorker\npublic class ExampleWorker extends Worker {\n\n private final WorkerDependency workerDependency;\n\n @AssistedInject\n ExampleWorker(\n @Assisted @NonNull Context context,\n @Assisted @NonNull WorkerParameters params,\n WorkerDependency workerDependency\n ) {\n super(context, params);\n this.workerDependency = workerDependency;\n }\n ...\n}\n```\n\nThen, have your [`Application`](/reference/android/app/Application) class\nimplement the `Configuration.Provider` interface, inject an instance of\n`HiltWorkFactory`, and pass it into the `WorkManager` configuration as follows: \n\n### Kotlin\n\n```kotlin\n@HiltAndroidApp\nclass ExampleApplication : Application(), Configuration.Provider {\n\n @Inject lateinit var workerFactory: HiltWorkerFactory\n\n override fun getWorkManagerConfiguration() =\n Configuration.Builder()\n .setWorkerFactory(workerFactory)\n .build()\n}\n```\n\n### Java\n\n```java\n@HiltAndroidApp\npublic class ExampleApplication extends Application implements Configuration.Provider {\n\n @Inject HiltWorkerFactory workerFactory;\n\n @Override\n public Configuration getWorkManagerConfiguration() {\n return new Configuration.Builder()\n .setWorkerFactory(workerFactory)\n .build();\n }\n}\n```\n| **Note:** Because this customizes the `WorkManager` configuration, you also must remove the default initializer from the `AndroidManifest.xml` file as specified in the [WorkManager docs](https://developer.android.com/topic/libraries/architecture/workmanager/advanced/custom-configuration).\n| **Warning:** `WorkManager` version `2.6.0-alpha01` or higher uses the `androidx.startup` initializer. To properly configure `WorkManager` in this version with Hilt, check out the [`WorkManager` release notes](https://developer.android.com/jetpack/androidx/releases/work#2.6.0-alpha01)."]]