https://kotlinlang.org logo
Title
f

Francois Morvillier

05/22/2023, 9:54 AM
Hi, I'm struggling to understand what circumstances can lead androidx.compose.runtime.Recomposer.applyAndCheck to throw:
Fatal Exception: java.lang.IllegalStateException
Unsupported concurrent change during composition. A state object was modified by composition as well as being modified outside composition.
I'm looking for a small code snippet that exhibits the problem and a link to where this behavior is documented.
s

shikasd

05/22/2023, 11:31 AM
It is caused by snapshot apply, most likely when two snapshots modified state in incompatible way at the same time, usually from different threads
You can read up more here: https://dev.to/zachklipp/introduction-to-the-compose-snapshot-system-19cn (see Conflicting snapshot writes)
Pretty sure there's some documentation about it, but not sure anything besides gdocs exist
f

Francois Morvillier

05/22/2023, 2:20 PM
Thanks for the link. I understand things a bit better but I still can't connect all the dots. I assume my error is caused by setting a MutableState somewhere? With regards to Compose, is it safe to set MutableState from any thread/coroutine? Or should I use withMutableSnapshot when not in the main thread or set a merge policy?
s

shikasd

05/22/2023, 2:28 PM
It is generally safe, you should use snapshot when you want to ensure consistency of update (e.g. when updating two connected states from bg thread) If you want to modify mutable state from both UI and bg threads, providing a mutation policy is desirable to ensure conflicts like yours can be resolved
f

Francois Morvillier

05/22/2023, 2:30 PM
I think my issue is that I'm modifying MutableState from the Compose function itself in some cases. That should always be avoided right?
s

shikasd

05/22/2023, 2:32 PM
It depends, but most likely you want to update it from effect
It is still possible to run into concurrency issues even in that scenario though
f

Francois Morvillier

05/22/2023, 4:04 PM
I'm going to put the updates in SideEffect as you suggest. Is there a doc that explains what to do and what no to do with regards to MutableState?