Why the registerApplyObserver callback isn't execu...
# compose
s
Why the registerApplyObserver callback isn't executing? Hasn't the global state already been updated from 0 to 10?
Copy code
@Test
    fun test19() {
        Snapshot.registerGlobalWriteObserver {
            println("$it")  // MutableState(value=10)@
            Snapshot.sendApplyNotifications()
        }
        Snapshot.registerApplyObserver { set, _ ->
            println(set.joinToString())  // !!! Expected MutableState(value=10)@, but it wasn't printed.
        }
        val snapshot1 = Snapshot.takeMutableSnapshot()
        var state: MutableState<Int>? = null
        snapshot1.enter {
            state = mutableStateOf(0)
            thread {
                println(state.value)  // 0
                state.value = 10
            }.join()
        }
        println(state?.value)  // 10
        snapshot1.apply().check()
        println(state?.value)  // 10
    }
s
This one is a bit tricky, you create a state and modify it in a global snapshot before applying the snapshot that created it. The initial value is technically invisible on the other thread, but we allow to read / write because it is a simpler model . Likely that triggers a bug where the state is a bit confused if it was written to? Worth reporting as a bug imho
s
I've seen many people confused about why the Compose UI doesn't update after updating the global state. It's easy for developers to write such code — for example, launching an IO coroutine to update the value before composition finishes. Even though the state is updated successfully, it fails to trigger recomposition.
s
LaunchedEffect is different - it will start after composition so you won't get this issue We generally recommend wrapping state updates with
withMutableSnapshot
if they happen on background thread to resolve some of the shortcomings here
Again - please file a bug, we are actively looking into some similar bugs right now
s