androidmvvmandroid-resources

MVVM: how to pass a resources string from view model to view?


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:

  1. the enum (e.g. GreetingType.GOODBYE)
  2. the resource ID (e.g. R.string.goodbye)
  3. the resolved string (e.g. context.resources.getString(R.string.goodbye)

Each approach seems to have downsides:

Is there a recommended approach?

Can I achieve both:

The examples I found only deal with data being displayed directly.


Solution

  • Can I achieve both:

    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)