I am developing an android app whit MVVM approach, and I need access to the SharedPreferences in the ViewModel, but I don't know how to do it.
I know that is possible access to the context of the class inherit from the AndroidViewModel, but I want to know is if possible, how to do it by injection.
For do the injection, I am using Dagger 2.
Thanks
It is possible. As you mentioned your ViewModel
has to extend AndroidViewModel
then just simply call getApplication()
and use it as context when accessing SharedPreferences
.
And for using Dagger 2 in ViewModel
: you cannot directly inject anything in ViewModel
either by parameter or field injection, for that you will need to use ViewModel Factory
and inject objects there first and pass them to whatever ViewModel
you want.
To learn more about using Dagger 2 with ViewModels
refer to this article.
UPDATE (2020-08-06):
It is possible to use Dagger 2 injections in ViewModels
, check Kotlin Clean Architecture library exmaples of how to use it.
https://github.com/android10/Android-CleanArchitecture-Kotlin