Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use @Immutable in compose?

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) { }
like image 238
Andrey Tuzov Avatar asked Oct 30 '25 18:10

Andrey Tuzov


1 Answers

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

like image 89
Denis Rudenko Avatar answered Nov 01 '25 08:11

Denis Rudenko