From 86c59d306ed445b2bf267563d8f3d0e78f6aaf28 Mon Sep 17 00:00:00 2001 From: Eric Bailey Date: Mon, 31 Aug 2026 12:52:23 -0500 Subject: [PATCH] Simplify native persisted write queue --- src/state/persisted/index.ts | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/state/persisted/index.ts b/src/state/persisted/index.ts index 136c3b5260..d792bc6ea1 100644 --- a/src/state/persisted/index.ts +++ b/src/state/persisted/index.ts @@ -21,7 +21,12 @@ export {defaults} from '#/state/persisted/schema' const BSKY_STORAGE = 'BSKY_STORAGE' let _state: Schema = defaults -let pendingWrite: Promise = Promise.resolve() +/** + * AsyncStorage persists the entire root state as one asynchronous write. This + * queue ensures each mutation computes from `_state` after the previous write + * commits instead of racing another whole-root snapshot. + */ +let enqueuedWrite: Promise = Promise.resolve() export async function init() { const stored = await readFromStorage() @@ -106,12 +111,20 @@ export async function clearStorage() { } clearStorage satisfies PersistedApi['clearStorage'] +/** + * Queues native root-state mutations while preserving their results for the + * caller. The queued operations run after the previous writes settle even when + * those writes failed. + */ function enqueueWrite(operation: () => Promise): Promise { - const result = pendingWrite.then(operation, operation) - pendingWrite = result.then( - () => undefined, - () => undefined, - ) + const result = enqueuedWrite.then(operation) + enqueuedWrite = (async () => { + try { + await result + } catch { + // The caller receives `result`; only the queue tail ignores its rejection. + } + })() return result }