How to use context in viewmodel with Hilt on Android

451 Views Asked by At

In my application I used MVVM and I have ViewModel, but I want access context into viewModel.
I write below codes into ViewModel :

@HiltViewModel
class SimpleViewModel @Inject constructor(
    private val repository: SimpleRepository, @ApplicationContext val context: Context
) : ViewModel() {

But show me warning in context and show me this message : This field leaks a context object

Wha is the best way for access context into viewmodel?

3

There are 3 best solutions below

2
On BEST ANSWER

As said here in this answer, when using @ApplicationContext there will be no leak, since the context will always outlive the View Model instance and this is just a false positive warning that you can even confirm doesn't happen by using the memory profiler.

You can ignore the warning by adding @SuppressLint("StaticFieldLeak") to your View Model class.

0
On

in viewModels or in any non activity file in android the context is there if you want context means then you have to create one Application file and declare the application file name in manifest application like

android:name = ".ApplicationFile"

and in that applicationFile you have to write a function like

val applicationScope = CoroutineScope(SupervisorJob())

override fun onCreate() {
    super.onCreate()
    appContext = applicationContext
    appPreferences = AppPreference(applicationContext)
}
companion object{
    var appPreferences: AppPreference? = null

    lateinit var appContext:Context
}in viewModels or in any non activity file in android the context is there

if you want context means then you have to create one Application file and declare the application file name in manifest application like

android:name = ".ApplicationFile"

and in that applicationFile you have to write a function like val applicationScope = CoroutineScope(SupervisorJob())

override fun onCreate() {
    super.onCreate()
    appContext = applicationContext
    appPreferences = AppPreference(applicationContext)
}
companion object{
    var appPreferences: AppPreference? = null

    lateinit var appContext:Context
}
0
On

In my opinion, in MVVM, we don't need context in the viewModel, because if the context is needed for the view's needs, then use the context in the Activity/Fragment/View itself. But if the context is needed to initiate a library in the repository (such as retrofit, room, etc.) use the application context from hilt.

Please feel free to comment about my opinion, because I'm still learning too.