In kotlin android development with jetpack compose and hilt, how to inject a viewmodel…
- User
In kotlin android development with jetpack compose and hilt, how to inject a viewmodel into a composable
- Assistant
In kotlin android development with jetpack compose and hilt, how to inject a viewmodel into a composable
To inject a ViewModel into a composable in Kotlin Android development using Jetpack Compose and Hilt, follow these steps:
Annotate Your ViewModel with @HiltViewModel
Use the @HiltViewModel annotation on your ViewModel class and utilize constructor injection with @Inject to get the dependencies. For example:
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class MyViewModel @Inject constructor(
private val repository: MyRepository
) : ViewModel() {
// ViewModel implementation
}
Here, MyRepository is a dependency that Hilt will provide to MyViewModel.
Use hiltViewModel() in Your Composable
In your composable function, obtain the ViewModel instance by calling the hiltViewModel() function:
import androidx.hilt.navigation.compose.hiltViewModel
@Composable
fun MyComposable(
myViewModel: MyViewModel = hiltViewModel()
) {
// Use myViewModel in your composable
}
The hiltViewModel() function retrieves the ViewModel from Hilt's dependency graph, ensuring that all dependencies are injected correctly.
Passing the ViewModel as a Parameter (Optional)
Alternatively, you can pass the ViewModel as a parameter to your composable if you need more control or for testing purposes:
@Composable
fun MyComposable(
myViewModel: MyViewModel
) {
// Use myViewModel in your composable
}
Then, when calling your composable, you can provide the ViewModel instance:
val myViewModel: MyViewModel = hiltViewModel()
MyComposable(myViewModel)
Additional Notes:
The hiltViewModel() function is part of the androidx.hilt library and is specifically designed to integrate Hilt with Jetpack Compose.
If you're using Jetpack Navigation Compose, hiltViewModel() will retrieve the ViewModel scoped to the appropriate NavBackStackEntry.
Ensure that you've set up Hilt properly in your application by adding the necessary dependencies and annotations in your application class and modules.
Example Setup:
Add Hilt Dependencies to Your build.gradle File:
dependencies {
implementation "com.google.dagger:hilt-android:2.44"
kapt "com.google.dagger:hilt-compiler:2.44"
implementation "androidx.hilt:hilt-navigation-compose:1.0.0"
}
Annotate Your Application Class with @HiltAndroidApp:
@HiltAndroidApp
class MyApplication : Application()
Inject Dependencies into Your ViewModel via Constructor:
class MyRepository @Inject constructor() {
// Repository implementation
}
By following these steps, you can seamlessly inject a ViewModel into a composable using Hilt and Jetpack Compose, benefiting from Hilt's dependency injection to manage your app's dependencies efficiently.
References:
Not yet included in a published release.