Skip to content

Commit

Permalink
refactor: move flushBatch in buildStore and call recomputeDependents …
Browse files Browse the repository at this point in the history
…directly
  • Loading branch information
dmaskasky committed Jan 7, 2025
1 parent 04734ef commit d092f6e
Showing 1 changed file with 26 additions and 29 deletions.
55 changes: 26 additions & 29 deletions src/vanilla/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,6 @@ type Batch = [
] & {
/** Atom dependents map */
D: Map<AnyAtom, Set<AnyAtom>>
/** Recompute dependents function */
R?: (batch: Batch) => void
}

const createBatch = (): Batch =>
Expand Down Expand Up @@ -229,32 +227,6 @@ const addBatchAtomDependent = (
const getBatchAtomDependents = (batch: Batch, atom: AnyAtom) =>
batch.D.get(atom)

const flushBatch = (batch: Batch) => {
let error: AnyError
let hasError = false
const call = (fn: () => void) => {
try {
fn()
} catch (e) {
if (!hasError) {
error = e
hasError = true
}
}
}
while (batch.D.size || batch.some((channel) => channel.size)) {
batch.R?.(batch)
batch.D.clear()
for (const channel of batch) {
channel.forEach(call)
channel.clear()
}
}
if (hasError) {
throw error
}
}

// internal & unstable type
type StoreArgs = readonly [
getAtomState: <Value>(atom: Atom<Value>) => AtomState<Value> | undefined,
Expand Down Expand Up @@ -574,6 +546,32 @@ const buildStore = (...storeArgs: StoreArgs): Store => {
}
}

const flushBatch = (batch: Batch) => {
let error: AnyError
let hasError = false
const call = (fn: () => void) => {
try {
fn()
} catch (e) {
if (!hasError) {
error = e
hasError = true
}
}
}
while (batch.D.size || batch.some((channel) => channel.size)) {
recomputeDependents(batch)
batch.D.clear()
for (const channel of batch) {
channel.forEach(call)
channel.clear()
}
}
if (hasError) {
throw error
}
}

const writeAtomState = <Value, Args extends unknown[], Result>(
batch: Batch,
atom: WritableAtom<Value, Args, Result>,
Expand All @@ -599,7 +597,6 @@ const buildStore = (...storeArgs: StoreArgs): Store => {
mountDependencies(batch, a, aState)
if (prevEpochNumber !== aState.n) {
dirtyDependents(batch, a, aState)
batch.R = recomputeDependents
registerBatchAtom(batch, a, aState)
}
return undefined as R
Expand Down

0 comments on commit d092f6e

Please sign in to comment.