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

Dominik Seemayr

02/16/2022, 6:07 PM
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

Albert Chang

02/16/2022, 6:28 PM
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

Dominik Seemayr

02/16/2022, 6:33 PM
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

Albert Chang

02/16/2022, 7:11 PM
Yep. Indirect read of the state will also work.
👍 1
d

Dominik Seemayr

02/16/2022, 7:52 PM
thanks man :))
c

Colton Idle

02/16/2022, 9:25 PM
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

Dominik Seemayr

02/16/2022, 9:27 PM
@Colton Idle i think the way @Albert Chang wrote it is the way you should do it (with private set) for basic states
t

tad

02/18/2022, 4:06 AM
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.