Why does `GlobalSnapshotManager` (in `androidx.com...
# compose
m
Why does
GlobalSnapshotManager
(in
androidx.compose.ui.platform
) start a coroutine on
AndroidUiDispatcher.Main
?
the
androidx.compose.ui.platform
implementation:
Copy code
internal object GlobalSnapshotManager {
    private val started = AtomicBoolean(false)
    private val sent = AtomicBoolean(false)

    fun ensureStarted() {
        if (started.compareAndSet(false, true)) {
            val channel = Channel<Unit>(1)
            CoroutineScope(AndroidUiDispatcher.Main).launch {
                channel.consumeEach {
                    sent.set(false)
                    Snapshot.sendApplyNotifications()
                }
            }
            Snapshot.registerGlobalWriteObserver {
                if (sent.compareAndSet(false, true)) {
                    channel.trySend(Unit)
                }
            }
        }
    }
}
mine:
Copy code
private object MyGlobalSnapshotManager {
    private val started = AtomicBoolean(false)
    private val pending = AtomicBoolean(false)

    fun start() {
        val manager = this
        if (!manager.started.compareAndSet(false, true)) {
            return
        }
        Snapshot.registerGlobalWriteObserver {
            if (manager.pending.compareAndSet(false, true)) {
                manager.pending.set(false)
                Snapshot.sendApplyNotifications()
            }
        }
    }
}
What does the
androidx.compose.ui.platform
implementation achieve by spawning a coroutine that mine fails to achieve? Their implementation seems to stop listening once the
AndroidUiDispatcher.Main
executor stops advancing the coroutine state, but why is it necessary to arrange that? If the main executor is ending, doesn’t that mean the app is closing? Why the need to specify ‘I’ll stop listening when the main thread is finishing’ – I couldn’t possibly keep listening if I wanted to
s
The coroutine is scheduled to be executed whenever thread is idle instead of sending apply notifications on each write, so it naturally batches states between frames
m
I was so utterly confused but that made it make sense – thanks for the reply!
@shikasd Is there an article that I can read to learn more about when the main thread becomes idle, and what ‘frames’ are and how they’re managed?
s