Yuuu
Yuuu

Reputation: 879

How to reference color resources from ViewModel in Jetpack Compose?

I'm new to Android development with Jetpack Compose. In my @Composable function, I have the following code to create a background gradient color list:

val backgroundColors = if (uiState.redGradient) {
    listOf(colorResource(R.color.customLightRed), colorResource(R.color.customPink)) 
} else {
    listOf(colorResource(R.color.customBlue), colorResource(R.color.customGreen))
}

My composable function is getting long so I want to move this gradient color logic to the ViewModel. However, when moved I get an error that "colorResource can only be called from a @Composable function".

Is there a way to reference color resources from a ViewModel? My goal is to observe the backgroundColors list from ViewModel in my Composable like:

val colors = viewModel.backgroundColors.value
// use colors for gradient

I'm unsure the best way to expose resources like colors from a ViewModel to use in Compose. Any guidance on the proper architecture or patterns to use here would be greatly appreciated!

Upvotes: 0

Views: 320

Answers (1)

Jigar Rangani
Jigar Rangani

Reputation: 386

try this

class YourViewModel : ViewModel() {
    private val _backgroundColors = MutableStateFlow<List<Int>>(emptyList())
    val backgroundColors: StateFlow<List<Int>> = _backgroundColors

    fun updateBackgroundColors(redGradient: Boolean) {
        val colorIds = if (redGradient) {
            listOf(R.color.customLightRed, R.color.customPink)
        } else {
            listOf(R.color.customBlue, R.color.customGreen)
        }
        _backgroundColors.value = colorIds
    }
}

and in you composable function access colors like this

 val backgroundColorIds = viewModel.backgroundColors.collectAsState()

    val backgroundColors = backgroundColorIds.value.map { colorResId ->
        colorResource(id = colorResId)
    }

Upvotes: 3

Related Questions