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

tad

03/08/2023, 12:19 AM
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

efemoney

03/08/2023, 4:06 AM
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

tad

03/08/2023, 4:07 AM
That's backward, MutableList.sort is the in-place version
e

efemoney

03/08/2023, 4:09 AM
Oh woops, my bad, then something is wrong somewhere
t

tad

03/08/2023, 4:11 AM
Yeah, it's because I need to call
list.toList()
to get the underlying immutable list for the snapshot
e

efemoney

03/08/2023, 4:12 AM
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

Zach Klippenstein (he/him) [MOD]

03/08/2023, 5:07 PM
This seems like a bug to me… if sorted doesn’t mutate the underlying list. Can you file?
t

tad

03/08/2023, 5:09 PM
Sure
z

Zach Klippenstein (he/him) [MOD]

03/08/2023, 8:52 PM
and please post here
t

tad

03/08/2023, 9:03 PM
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
.
109 Views