https://kotlinlang.org logo
Title
k

K Merle

02/01/2022, 7:12 AM
What would be most optimal way to convert hex color to a Compose Color, and to avoid recreation of an object on recomposition? Colors are mainly used inside
LazyColumn
. Only thing I could think of is using
remember
, but I'd still would have to use
remember
inside
LazyColumn
.
a

Albert Chang

02/01/2022, 8:32 AM
The (pseudo) constructors of
Color
are marked with
@Stable
so the runtime should have already done the optimization (i.e. only calling the function again if parameters changed).
k

K Merle

02/01/2022, 9:09 AM
Would setting a
@Stable
annotation to something like this optimize function on recomposition?
fun String?.toComposeColor(alpha: Int = 0xFF, defaultColor: Color = Color.Transparent): Color {
    if (this.isNullOrEmpty()) return defaultColor
    val color = android.graphics.Color.parseColor(this)
    return Color(red = color.red, green = color.green, blue = color.blue, alpha = alpha)
}
a

Albert Chang

02/01/2022, 9:11 AM
Yep.
a

Andrey Kulikov

02/01/2022, 11:33 AM
Color is an inline class so there is no object creation involved, you don’t need to optimize that. using remember would be even less efficient as in order to be remembered the inline class would have to be boxed