I want to display a text in my view. However, the text is not dependent of "data" from my model I can display directly but depends on a state enum. Dependent of the state I want to display a pre-defined text in my string resources file.
For example, I have the following enum in the model layer:
enum class GreetingType
{
GREETING_FIRST_TIME,
WELCOME_BACK,
GOODBYE
}
In my strings.xml I have the respective strings:
R.string.greeting_first_time
R.string.welcome_back
R.string.goodbye
My question is: How should the interface between view model and view look like? Should I pass:
GreetingType.GOODBYE
)R.string.goodbye
)context.resources.getString(R.string.goodbye
)Each approach seems to have downsides:
context
in the view model, which I would like to avoid.Is there a recommended approach?
Can I achieve both:
ViewModel
instead of AndroidViewModel
)?The examples I found only deal with data being displayed directly.
Can I achieve both:
Keep the view dumb (by avoiding if/else)
Keep the view model clean of the Android Framework (i.e. use ViewModel
instead of AndroidViewModel
)?
You can satisfy both of these conditions with TextResource. This will allow you to build your string in the ViewModel (without a context) and resolve it in the UI
// ViewModel
val title = TextResource.simple(R.string.greeting, userName) // expose via Flow or LiveData
// Compose
Text(title.resolveString())
// Views
textView.text = title.resolveString(context)