# compose

Christopher Mederos

06/27/2023, 7:21 AM
SnapshotStateList is great to use when state doesn't need to be hoisted outside the composable. In particular, remove() and removeRange() are extremely useful.
Copy code
remember { mutableStateListOf("item 1", "item 2", "item 3") }
However - what is the best practice when you would like to store the list items in a view model? In my case, I'm trying to keep track of a list of things a user enters into a form and eventually uploading it to a server.


06/27/2023, 7:46 AM
Aren't they mostly wrapping the kotlin immutable collections?
So wrap a persistent collection in a StateFlow?


06/27/2023, 12:48 PM
Can’t you just use
in your ViewModel?

Zach Klippenstein (he/him) [MOD]

06/28/2023, 5:08 AM
Imo the simplest thing is to just continue to use mutableStateListOf in your VM. But if you’re willing to depend on the (not yet stable) kotlin persistent collections lib, you can use those with a lot of common architecture patterns that assume immutable values, and put them in MutableStateFlow, MutableState, or whatever.

Christopher Mederos

06/29/2023, 2:45 AM
Thank you for the input everyone! I found using persistent collections from kotlinx fit my pattern best (thanks for the headsup @Zach Klippenstein (he/him) [MOD]). I'll briefly explain my patterns around state, view model, and composables so you can see how it fits nicely for me - • I'm collecting state at the top level composable on my screen:
val uiState by myViewModel.collectAsState()
• My view model is supporting a long input form • My state is held in the ViewModel as a private data class:
val _uiState = MutableStateFlow(MyUiState())
• My state model has many fields that are related to a user recording information for a single report. Something like -
Copy code
data class MyUiState constructor(
    val firstName: String = "",
    val lastName: String = "",
    val hobbies: PersistentList<String> = persistentListOf()
• I'm updating state using MutableStateFlow.update() and copying state to emit new values
Copy code
fun addHobby(newHobby: String) {
    _uiState.update { it.copy(hobbies = it.hobbies.add(newHobby)) }

Colton Idle

06/29/2023, 9:00 PM
I thought I read somewhere that even if you use a Flow in your VM, and then you collectAsState (or w/e), internally everything still has to convert to a snapshot state... and so... snapshot state could be better to just use directly unless you had some Flow specific code? Not sure if that's true or not, but I think im remembering correctly.

Zach Klippenstein (he/him) [MOD]

06/29/2023, 9:01 PM
is just
, which is just
with a