0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(自分用メモ)Hiltで依存関係を追加する

Posted at

1. 依存関係を追加する

ドキュメント

まずルートの gradle にプラグインを追加

build.gradle.kts
plugins {
  ...
  id 'com.google.dagger.hilt.android' version '2.51.1' apply false
}
トップレベルの gradle の記述について 全てのモジュールで同じ plugin バージョンを使用するため、トップレベルのGradle でバージョン付きの plugin を宣言している。
こうすることで、モジュール側ではバージョンを書かずに plugin を宣言することができる。
トップレベルでは宣言のみを行なって plugin の使用はしないので、 apply false を設定している。
https://developer.android.com/build/migrate-to-kotlin-dsl?hl=ja&utm_source=chatgpt.com#perform-refactoring

それからappモジュールの gradle に依存関係を追加

app/build.gradle.kts
plugins {
  id("kotlin-kapt")
  id("com.google.dagger.hilt.android")
}

android {
  ...
}

dependencies {
  implementation("com.google.dagger:hilt-android:2.51.1")
  kapt("com.google.dagger:hilt-android-compiler:2.51.1")
}

// Allow references to generated code
kapt {
  correctErrorTypes = true
}

2. Application クラスにアノテーションを付与する

MainApplication.kt
@HiltAndroidApp
class MainApplication : Application() { ... }

3. Activity / Fragment にアノテーションを付与する

依存関係を受け取る側に @AndroidAnnotation のアノテーションを付与する
https://developer.android.com/training/dependency-injection/hilt-android?hl=ja#android-classes

@AndroidEntryPoint
class ExampleActivity : AppCompatActivity() {

  @Inject lateinit var analytics: AnalyticsAdapter
  ...
}

4. ViewModel にアノテーションを付与する

ExampleViewModel.kt
@HiltViewModel
class ExampleViewModel @Inject constructor(
  private val savedStateHandle: SavedStateHandle,
  private val repository: ExampleRepository
) : ViewModel() {
  ...
}

5. 依存関係を受け取る側に依存関係を注入する

ExampleActivity.kt
@AndroidEntryPoint
class ExampleActivity : AppCompatActivity() {
  private val exampleViewModel: ExampleViewModel by viewModels()
  ...
}

5'. Composable 関数に viewModel の依存関係を注入する

まず以下の依存関係を追加する。

build.gradle.kts
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.5")

すると viewModel() 関数を使用して Composable 関数に viewModel を追加できる

MyScreen.kt

// import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun MyScreen(
    viewModel: MyViewModel = viewModel()
) {
    // use viewModel here
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?