When playing with Snapshot system, I find if I tak...
# compose
r
When playing with Snapshot system, I find if I take a snapshot and create a
state: State<T>
in it, then dispose the snapshot, the created
state
can’t be read from
GlobalSnapshot
, which makes sense. However if anything triggered
advanceGlobalSnapshot
(for example
registerApplyObserver
), the new
GlobalSnaphot
will be able to read the
state
now (because the new
GlobalSnapshot
no longer remember the disposed snapshot in invalid snapshots). Is this a bug?
To repro
Copy code
@Test
    fun `test state created in inner snapshot can be read from outer snapshot`() {
        var stateCreatedInSnapshot: MutableState<Int>? = null
        Snapshot.takeSnapshot().run {
            try {
                enter { stateCreatedInSnapshot = mutableStateOf(0) }
            } finally {
                dispose()
            }
        }
//        Snapshot.registerApplyObserver { _, _ -> } // with this line the following line will NOT explode
        println("stateCreatedInSnapshot=${stateCreatedInSnapshot?.value}")
    }
s
I'm not sure but I think any created state is also in global but only after its snapshot is commited(which I think is happening in with advanceGlobalSnapshot)
The question is if state created in already disposed snapshots will also be commited to global.
r
I think a readonly snapshot can’t be committed/applied right? And
advanceGlobalSnapshot
shouldn’t automatically commit any snapshots. (I could be wrong since I’m new to snapshots)
s
yes you are right. Nothing is commited by advanceGlobalSnapshot
This is an excellent source on this topic

https://www.youtube.com/watch?v=waJ_dklg6fU

r
Thanks, that’s very informative! On the other hand, I still feel the code above is buggy, depending on which mindset is more correct 1. Readonly snapshots means the snapshot can’t make modifications to outer snapshot, but the snapshot itself can have internal state. In this case, I think it makes sense to let `MutableState`s in read only snapshot writable (which are currently not), as long as we ensure the effect won’t escape from the readonly snapshot. 2. Readonly snapshots means the snapshot can’t have any kind of writes, in this case I think we should disallow creating mutableState in readonly snapshots at all.
z
Good questions. @Chuck Jazdzewski [G]?
c
1 is rather confusing. 2 is probably right but would be difficult to land now.
r
Thanks! Regarding current situation, would it be better if we can keep `mutableState`s created in readonly snapshot invalid, no matter how many times we call
advanceGlobalSnapshot
?