androidkotlindagger-hilt

Inject context with Hilt: this field leaks a context object


I'm using Hilt to inject context and other dependencies into my HomeViewModel class; Everything is working properly but I'm getting this warning. How can I prevent from leakings?

This is my HomeFragment (where I inject and use the HomeViewModel class):

@AndroidEntryPoint
class HomeFragment : Fragment() {

private val viewModel: HomeViewModel by viewModels()

....

}

This is the warning:

Hilt injection viewModel

class HomeViewModel @ViewModelInject constructor(
    @ApplicationContext val context: Context,
    private val locationAPI: LocationAPI,
    private val imagesAPI: ImagesAPI
) :
    ViewModel() {
...
}

I'm using:

//Hilt DI
implementation "com.google.dagger:hilt-android:2.30.1-alpha"
kapt "com.google.dagger:hilt-android-compiler:2.30.1-alpha"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02"
kapt "androidx.hilt:hilt-compiler:1.0.0-alpha02"

Thanks!

-- Edited, as suggested, after the first given answer:

The Home Fragment now is:

enter image description here

@HiltViewModel
class DetailsViewModel @Inject constructor(
    @ApplicationContext val context: Context,
    private val locationDetailsAPI: LocationAPI) :
    ViewModel() {
...

}

Dependencies updated to:

//Hilt DI
implementation "com.google.dagger:hilt-android:2.31-alpha"
kapt "com.google.dagger:hilt-android-compiler:2.30.1-alpha"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
kapt "androidx.hilt:hilt-compiler:1.0.0-alpha03"

And I'm still getting this leaking error.

Any ideias?


Solution

  • I don't get this warning, and I inject a context the same way.

    Try updating to 2.31.2-alpha for hilt and 1.0.0-alpha03 for hilt-androidx

    There are a few breaking changes. You will need to annotate your view models with @HiltViewModel, use @Inject instead of @ViewModelInject. And you will need to replace any references to ApplicationComponent with SingletonComponent.