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?
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.