how can we sort a SnapshotList. is it better just ...
# compose
m
how can we sort a SnapshotList. is it better just to create a new list i supposed. notification spam ?
d
Copy, sort, clear and addAll.
There may be a mutable snapshot API you could use but I've never tried it.
z
If you're doing it on the main thread you don't need to create an explicit snapshot, you can just sort the list in-place. If you're doing it off the main thread, you can wrap in a
Snapshot.withMutableSnapshot {}
.
m
ya, main thread, so i can just clear addAll and it wont trigger multiple notifications?
what is withMutableSnapshot, an extension? cant find it
z
Change notifications are not actually sent when a snapshot state object is changed, they're only sent when a snapshot is committed, regardless of how many times an object was changed in that snapshot. If you're on the main thread and not in a composition, the snapshot in question is the global snapshot, which gets committed just before the next frame
c
Change notifications are not actually sent when a snapshot state object is changed, they're only sent when a snapshot is committed
oh hm. TIL
f
What if multithreaded recomposition was working? Would running on the main thread ensure that the state won't be commited during the sorting? 🤔 Or will SnapshotState not be impacted by multithreaded recomposition because that will only impact the actual calculation of the UI? Does the question even makes sense? 😅 It's not really important, I am just curious 😅
z
If you’re in a composition then the compose runtime is already ensuring you’re in a snapshot, whether that’s on the main thread or in the future when multithreaded composition is working
Although i doubt you’d want to be sorting a list directly in a composition
But if you’re in a snapshot, it doesn’t matter what thread you’re on, it’s like a transaction and you won’t see changes to any snapshot state objects from other threads until you commit or dispose your snapshot (and other threads won’t see your changes until then either)
m
ya, thanks. So it would be something like this:
Copy code
val list = mutableStateListOf<Unit>()
Snapshot.withMutableSnapshot {
    list.sortBy {  } ..
}
?
👍🏻 1
c
oh thats really cool. I've definitely had some sort operations, i.e. sort, clear list, add new sorted list to list. Seems like I should have wrapped all of that in a Snapshot.withMutableSnapshot { }
m
If you are using the main thread, dont bother 😛 otherwise ya
c
Oh yeah. I guess I'm using the main thread typically i do this with a firebase observable that I observe in my VM. Something like this
Copy code
VM {
  init {
    viewModelScope.launch {
      firestore.observeTodoItems {
        val sorted = it.sort()
        state.todos.clear()
        state.todos.addAll(sorted)
      }
    }
  }
}
f
Sorry for returning to this thread after two weeks but I keep thinking about this 😅 I am preparing meetup talk about Snapshots and would love to talk about this. But I can't find good code example that will show why it's bad idea to change state from different (non-Main) thread without
Snapshot.withMutableSnapshot { ... }
.
z
Probably the usual race condition stress test should work: two threads running tight loops that modify a single state with multiple read+write ops.
Copy code
val counter by mutableStateOf(0)
val iterations = 10_000
val parallelism = 5

repeat(parallelism) {
  launch(Dispatchers.Default) {
    doWork()
  }
}
Copy code
suspend fun doWork() {
  repeat(iterations) {
    counter = counter + 1
  }
}
Counter should be a mostly random number at the end and different on each run.
To fix you'll also need to specify a merge policy. The code sample in the docs for that parameter to mutableStateOf should cover it
f
Yes, this is some extreme example that would show the benefits of Snapshots but previously in this thread you wrote
.... If you're doing it off the main thread, you can wrap in a
Snapshot.withMutableSnapshot {}
.
when talking about sorting a list in place. I thought the reason is that the global snapshot could be advanced during this operation resulting in frame that has only part of the list sorted. Is that not the reason? If it is, how can I show it in an example? Because while your example show the benefits of Snapshots, it's usually not this extreme in real world scenario. I've been reading about and playing with snapshots (in Compose UI) for a while but I feel like something is still not clicking for me. You know the feeling, like I'm missing something simple and obvious but I am just overthinking it.
z
That tends to be how race conditions like this work - they seem unlikely but when they happen they are extremely hard to find and debug
a
@Zach Klippenstein (he/him) [MOD] how merge policy for this case should looks like? Following one still provides weird results
val counter = mutableStateOf(0, object : SnapshotMutationPolicy<Int> {
override fun equivalent(a: Int, b: Int) = false // comparison make no sense
override fun merge(previous: Int, current: Int, applied: Int): Int {
return current + (applied - previous)
}
})
Doc's sample specified
fun equivalent(a: Int, b: Int): Boolean = a == b
which looks weird (for multithreaded environment). Imagine case:
Snapshot1 reads 0
Snapshot2 reads 0
Snapshot1 increment
Snapshot2 increment
Snapshot1 apply ->
equivalent(0, 1) ->
merge(0, 0, 1)
Snapshot2 apply ->
equivalent(1, 1) -> skip; // lost 1
But even my variant with
equivalent() = false
still produces weird results (e.g. 98 instead of 100). I guess it's due to`optimisticMerges`