Home > Enterprise >  Read-only mutableStateListOf
Read-only mutableStateListOf

Time:02-17

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.

CodePudding user response:

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
  • Related