I would like to share a technique to access the strings in view model that works well.
So there are multiple ways to access the string in view model but they have there own advantages and disadvantages.
We have options like
- Hardcode a string in code but this will not help in case of reusability and string localisation
- Use the context of an activity but in mvvm its bad practice to use context direct in view model
- Return the string resource id which is integer and in activity get the actual string but this will increase the efforts
Let's move toward the solution
In MVVM and hilt will have addition benefits to overcome above issue.
We will add the StringResourcesProvider.kt
@Singleton
class StringResourcesProvider @Inject constructor(
@ApplicationContext private val context: Context
) {
fun getString(@StringRes stringResId: Int): String {
return context.getString(stringResId)
}
}
Define the view model to get the string
@HiltViewModel
class AuthViewModel @Inject constructor(
private val stringResourcesProvider: StringResourcesProvider
) : ViewModel() {
...
fun validate() {
val username: String = stringResourcesProvider.getString(R.string.username)
}
...
}
In this way we can access the string in view model or any other places.
Thanks for reading my post.
Happy codding
Top comments (0)