Where should I place Immutable annotation to enable composition optimizations ? 1, 2 or/and 3 and why ?
It confused me that standart VisualTransformation interface for TextField has this annotation, but PasswordVisualTransformation doesn't and @Immutable is not inherited
// 1 - @Immutable
sealed class State(val option1: String) {
// 2 - @Immutable
object One : State("")
// 3 - @Immutable
data class Two(val option2: String) : State("")
}
@Composable
fun Screen(state: State) { }
First option is sufficient. You can double check this using compose compiler metrics report or skipped recompositions and changing:
data class Two(val option2: String) : State("")
to
data class Two(var option2: String) : State("")
Using var will make sure to mark Two as unstable by the compiler, so you will see the benefit of @Immutable annotation. Without this change - composable will be marked as skippable and stable anyway, so you won't notice any difference.
Also there is no need to mark classes as Stable/Immutable unless you create a library for someone to use or have multi-module project
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With