Read-only mutableStateListOf
Asked Answered
D

1

4

In Jetpack Compose, if I have a MutableState variable, I can expose it's State as "read-only" value to other classes as State<String>, just like:

private val _title = mutableStateOf("abc")
val title: State<String> = _title

Is there a way to do this with SnapshotStateList<> too? How would I do this for example with:

private val _titles = mutableStateListOf<String>(...)
val titles: ??? = _titles

I know that I could work around this by just using MutableState<List<String>>, but I'd have to provide a whole new list every time I would want to add/remove items.

Disgust answered 16/2, 2022 at 18:30 Comment(0)
M
4

mutableStateListOf create an object of SnapshotStateList, which is subclass of MutableList, so you can use List:

val titles: List<String> = _titles

Also with mutableStateOf you can use a single variable with delegation:

var title by mutableStateOf("abc")
    private set
Mazurek answered 16/2, 2022 at 18:54 Comment(2)
Oh wow, so if I use the "immutable List" titles in a composable, compose would know there's a State-object behind that to observe and still recomposes when _titles changes?Disgust
@DominikSeemayr this doesn't change actual type of _titles, that's why state object works as expected.Mazurek

© 2022 - 2024 — McMap. All rights reserved.