https://kotlinlang.org logo
#compose
Title
# compose
d

Daniel Okanin

05/02/2022, 5:59 PM
Hi everyone , I have a question about @Stable annotation. I have the following class model with a List as a field. List considers as unstable field (check it in the compose metrics), so if I change the list content the composable functions that use this model will be recomposed again? Should I wrap the list under MutableState object? Thanks
Copy code
@Stable
class PhotoViewModelItem(
    val id: String?,
    val title: String?,
    val savedGalleries: List<String>?,
)
a

agrosner

05/02/2022, 6:38 PM
I replaced usages of
List
with this:
Copy code
import androidx.compose.runtime.Immutable
import java.util.Collections

/**
 * Use this list instead of [List] as compose cannot infer list types properly.
 */
@Immutable
data class ImmutableList<T>
internal constructor(
    val list: List<T>
) : List<T> by list

/**
 * Constructs an [ImmutableList] with the specified [list].
 * We copy the passed in list to ensure its fully immutable.
 */
fun <T> immutableListOf(list: List<T>): ImmutableList<T> = ImmutableList(Collections.unmodifiableList(list))

/**
 * Constructs an [ImmutableList] with the specified [list].
 */
fun <T> immutableListOf(vararg items: T): ImmutableList<T> = ImmutableList(
    Collections.unmodifiableList(
        items.toList(),
    )
)

/**
 * Converts a list to an immutable kind.
 */
fun <T> List<T>.toImmutableList(): ImmutableList<T> = immutableListOf(this)

fun <T> Array<T>.toImmutableList(): ImmutableList<T> = ImmutableList(Collections.unmodifiableList(this.toList()))
best I can do to enforce it from an API perspective to ensure its marked as stable
d

Daniel Okanin

05/02/2022, 7:50 PM
Thanks @agrosner so List field in @Stable class is same as @Stable class with state field?
a

agrosner

05/02/2022, 8:41 PM
im confused, what do you mean?
10 Views