Hi! What do you do when you need to use colors ins...
# compose
a
Hi! What do you do when you need to use colors inside a mapper, which is injected to your viewModel via DI? I’ll provide details in a thread below
Suppose you have some States coming from a backend which you color code in presentation layer by mapping enum values to Colors
Copy code
fun mapApiStateToColor(state: State): Color =
when (state) {
    State.On -> Color.MyRed
    State.Off -> Color.MyBlue
}
to respect Dark/Light themes I use a local variable in my mapper class
Copy code
private val isInDarkMode =
        (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
But the thing is, that when I change a theme when application is running, the
isInDarkMode
not changed and all the UI is updated apart from this case. In a mapper function I use this variable like:
Copy code
if (isInDarkMode) Color.MyLightRed else Color.MyRed
Firstly, I tried to use colors from my theme and determine whether the dark mode is on by a composable function
isSystemInDarkTheme()
, but as we know it must be called from a composable scope and it seemed impossible to use
@Composable
annotation in the DI module. The DI framework broke on generating necessary code.
c
I think the best you can do is not mapping the colors in the VM, just passing down the
State
as is, and assigning the proper color to it in your View layer
👍🏽 1
👍 5
j
I agree with Csaba, plus I don’t see the point of injecting mappers instead of they be static functions
What is the utility to being able to replace a mapper?
a
The mapper is already in presentation layer and it’s injected into VM as a constructor field, but I see your point. I’ll try to rearrange this logic and remove injection as it provides more inconvenience than profit. Thanks!
j
you can just move it to an extension function, but anyway, I would map in the UI
a
Yeah, the Csaba’s suggestion is the only fully working option for me, cause I use this mappers for RecyclerView items which is loaded with pagination. Am I right in assuming that when I’ll switch to LazyColumn with compose paging all the logic for items will be in compose and I wouldn’t face the same problem?