If I have a `MutableState`, I can expose it as rea...
# compose
d
If I have a
MutableState
, I can expose it as read-only value to other classes as
State<String>
, just like:
Copy code
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:
Copy code
private val _titles = mutableStateListOf<String>(...)
val titles: ??? = _titles
1
a
Copy code
val titles: List<String>
    get() = _titles
Also the
MutableState
case can be simplified to:
Copy code
var title by mutableStateOf("abc")
    private set
☝️ 1
d
Thanks @Albert Chang! Tho, if a composable would use this titles variable, would it be recomposed when _titles changes? Since it's not aware of a State object, but just a List<String>. Or is compose smart enough for that?
a
Yep. Indirect read of the state will also work.
👍 1
d
thanks man :))
c
Is this a common pattern? I remember following this backing property pattern for live data but I haven't done it with compose and it seems to be no worse off.
d
@Colton Idle i think the way @Albert Chang wrote it is the way you should do it (with private set) for basic states
t
It depends on when you want the read to happen.
State<T>
allows consumers to obtain the state holder without performing a read, while
var ... by mutableStateOf(...)
forces a read when the field is accessed.