I appear to be confused about snapshot state. The ...
# compose
t
I appear to be confused about snapshot state. The following code crashes with a ConcurrentModificationException, presumably when the source SnapshotStateList is modified while sorting in
derivedStateOf
.
Copy code
private val list = mutableStateListOf<Thing>()

val sortedList by derivedStateOf {
    list.sorted()
}
Do I need to be protecting against modifications to the state I read in
derivedStateOf
blocks?
I see now that
toList()
is intended to be used to get the PersistentList for the current snapshot record, so you can iterate without dealing with concurrent modifications. It's a bit concerning that using standard Kotlin library functions such as
map
,
fold
,
filter
, etc. run the risk of crashing unless this is used. Would it make sense to have
iterator()
return
toList().iterator()
instead of the SnapshotStateList's
ListIterator
implementation?
Ah, that wouldn't work because of the
MutableList
interface's contract that
iterator()
returns a
MutableIterator
. Feels like a footgun inherited by Java.
e
List.sorted doesnt realy make sense for derived state & snapshot state list because you are modifying the snapshot state list while its trying to run the derived block. You need List.sort() which creates a new list that is sorted from the first one.
t
That's backward, MutableList.sort is the in-place version
e
Oh woops, my bad, then something is wrong somewhere
t
Yeah, it's because I need to call
list.toList()
to get the underlying immutable list for the snapshot
e
Yeah I use the
toList()
version everywhere (i also have a derived sorted list too) so I haven’t run into this. But I agree it should be somewhat clarified
z
This seems like a bug to me… if sorted doesn’t mutate the underlying list. Can you file?
t
Sure
z
and please post here
t
I'm reporting now, but as I'm writing this it strikes me that it's not really a problem with Compose, but more of a problem with the List/MutableList interface.
Like, this would happen if it were a
MutableList
instead of a
SnapshotStateList
.
155 Views