I am using Dagger 2 DataBindng
and the new Android Lifecycle components, which have ViewModels
.
Inside my ViewModel
how could I get access to my strings.xml? I was thinking at first, to inject a Context
into the viewModel
, however, this will just leak memory.
Are there any other ways?
Just create a ResourceProvider class that fetch resources using Application context. In your ViewModelFactory instantiate the resource provider using App context. You're Viewmodel is Context free and can be easily testable by mocking the ResourceProvider.
XML file saved at res/values/strings.
The AndroidViewModel extends ViewModel , so it has all the same functionality. The only added functionality for AndroidViewModel is that it is context aware: when initializing AndroidViewModel you have to pass the Application context as a parameter.
Can we use context in ViewModel Android? 1. No Android Framework references in ViewModel. It is a good practice (but not mandatory) to keep ViewModel free from Android framework references like Activity, Context, Drawables etc.
There is an AndroidViewModel
, which receives Application
instance as parameter.
From docs:
Application context aware ViewModel.
Subclasses must have a constructor which accepts Application as the only parameter.
You can retrieve a string from strings.xml
using that parameter.
The repo in the link, however uses ViewModel and not AndroidViewModel. If I extend my ViewModel to use AndroidViewModel and include the Application - it's trying to inject MyApplication instead of Application if that makes sense.
I've checked out GithubBrowserSample. Here's how UserViewModel
looks like:
public class UserViewModel extends ViewModel {
...
@Inject
public UserViewModel(UserRepository userRepository, RepoRepository repoRepository) {
...
}
...
}
And here's what changes I've done:
public class UserViewModel extends AndroidViewModel {
...
@Inject
public UserViewModel(Application application, UserRepository userRepository, RepoRepository repoRepository) {
super(application);
...
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With